//
//  CXmppMgr.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/4/7.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "CXmppMgr.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "XMPPLogging.h"
#import "MicroDef.h"
#import "CFolderMgr.h"
#import "CServerSettingMgr.h"
#import "CServerSettingModel.h"
#import "CRequestMgr.h"
#import "CRequestModel.h"
#import "CXmppRequestMgr.h"
#import "CDepartmentMgr.h"
#import "CDepartmentModel.h"
#import "CContactModel.h"
#import "CContactMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "CUserSettingMgr.h"
#import "CUserSettingModel.h"
#import <AudioToolbox/AudioToolbox.h>
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "CGroupMemberMgr.h"
#import "CGroupMemberModel.h"
#import "SDWebImageManager.h"
#import "NSString+MyString.h"
#import "CRecentlyContactModel.h"
#import "CRecentlyContactMgr.h"
#import "CCompany.h"
#import "CCompanyMgr.h"
#import "LoginViewController.h"
#import "CMessageDraftMgr.h"
#import "UIUtil.h"
#import "CPresenceMgr.h"
#import "CPresenceModel.h"
#import "CShareMgr.h"
#import "CAttentionMgr.h"
#import "CMineAttentionContact.h"
#import "CShareCommentMgr.h"
#import "CShareCommentDelMgr.h"
#import "CShareMgr.h"
#import "CShareDelMgr.h"
#import "MJExtension.h"
#import "EFengShare.h"
#import "EFengShareCommentDel.h"
#import "EFengShareDel.h"
#import "EFengContent.h"
#import "CSharePersonMgr.h"
#import "WZSafeArray.h"
#import "WZSafeDict.h"
#import "ChildHoodService.h"
#import "CXmppRequestMgr.h"
#import "SDWebImageManager.h"
static const void * const CXmppMgrDispatchQueueSpecificKey = &CXmppMgrDispatchQueueSpecificKey;

@interface CXmppMgr()<XMPPStreamDelegate,XMPPReconnectDelegate>

- (void)setupStream;

- (void)goOnline;
- (void)goOffline;
StrongProperty WZSafeDict *safeDict;
StrongProperty NSLock *lock;
StrongProperty NSTimer *timer;
StrongProperty NSTimer *resendTimer;
StrongProperty CContactMgr *contactMgr;
StrongProperty CGroupMgr *groupMgr;
StrongProperty CMessageMgr *messagrMgr;
@end

@implementation CXmppMgr

@synthesize xmppStream;
@synthesize xmppReconnect;

@synthesize xmppAutoPing;

+(CXmppMgr *)shareInstance
{
    static CXmppMgr *instance  = nil;
    static dispatch_once_t dispatch_onces;
    if(instance  == nil)
    {
        dispatch_once(&dispatch_onces, ^{
            
            instance = [[CXmppMgr alloc] init];
        });
    }
    return instance;
}

- (WZSafeDict *)safeDict
{
    if (_safeDict == nil) {
        _safeDict = [[WZSafeDict alloc] init];
    }
    return _safeDict;
}


-(id)init
{
    self = [super init];
    if(self)
    {
        [self setupStream];
        self.contactMgr = [[CContactMgr alloc] init];
        self.groupMgr = [[CGroupMgr alloc] init];
        self.messagrMgr = [[CMessageMgr alloc] init];
        self.noticeNum = 0;
        self.xmppMgrQueen = dispatch_queue_create([[NSString stringWithFormat:@"CXmppMgr.%@", self] UTF8String], DISPATCH_QUEUE_CONCURRENT);
        dispatch_queue_set_specific(_xmppMgrQueen, CXmppMgrDispatchQueueSpecificKey, (__bridge void *)self, NULL);
//        self.timer = [NSTimer timerWithTimeInterval:120 target:self selector:@selector(checkMessage) userInfo:nil repeats:YES];
        self.resendTimer = [NSTimer timerWithTimeInterval:30 target:self selector:@selector(loadunSendComment) userInfo:nil repeats:YES];
        [self performSelectorInBackground:@selector(addTimer) withObject:nil];
        
    }
    return self;
}

- (void)addTimer
{
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] addTimer:self.resendTimer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}
//bug 8985 fixed by lixu
-(void)loadunSendComment
{
    if ([USER_DEFAULT boolForKey:@"sendOK"]) {

        NSArray *unsendShareArray = [[[CShareMgr alloc]init] getAllUnsendShare];
        if (unsendShareArray.count>0) {
            CContactModel *curContact = [[[CContactMgr alloc]init] loadCurContact];
            [unsendShareArray enumerateObjectsUsingBlock:^(EFengShare *share, NSUInteger idx, BOOL * _Nonnull stop) {
                NSMutableArray *imageArray = [NSMutableArray array];
                for (NSDictionary *dic in share.imageName) {
//                    UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:dic[@"url_max"]];
                    NSString *path = [[ChildHoodService defaultService] personalUploadImagePathWithUserId:curContact.UserID];
                    NSString *imagePath = [path stringByAppendingPathComponent:dic[@"url_max"]];
                    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                    if (image != nil) {
                         [imageArray addObject:image];
                    }
                   
                }
                NSString *path = [[ChildHoodService defaultService] personalUploadVideoPathWithUserId:curContact.UserID];
                NSString *videoPath = [path stringByAppendingPathComponent:share.videoName.firstObject[@"video"]];
                NSData *videoData = [NSData dataWithContentsOfFile:videoPath];
              [[CXmppRequestMgr shareInstance] composeShareWithContact:curContact sharId:share.shareId content:share.content type:share.releaseType imageArray:imageArray videoData:videoData visibleUseId:@"all" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                  if ([responseObject[@"result"] isEqualToString:@"success"]) {
                                              share.date = [NSString stringWithFormat:@"%@",responseObject[@"date"]];
                                              share.shareId = [NSString stringWithFormat:@"%@",responseObject[@"id"]];
                                              [[[CShareMgr alloc]init] updateShareWithShareId:share.shareId date:share.date];
                                              [[[CSharePersonMgr alloc]init] updateShareWithShareId:share.shareId date:share.date];
                                              [USER_DEFAULT setBool:YES forKey:@"sendOK"];
                                              [USER_DEFAULT synchronize];
                                          }

              } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                  
              }];
 
            }];
        }
        NSArray *unsendArray = [[[CShareCommentMgr alloc]init] getUnsendCommentList];
        if (unsendArray.count>0) {
            [unsendArray enumerateObjectsUsingBlock:^( EFengContent *content, NSUInteger idx, BOOL * _Nonnull stop) {
                EFengShare *share = [[[CShareMgr alloc]init] getShareWithShareId:content.shareId];
                [[CXmppRequestMgr shareInstance] composeShareCommentWithShareId:content.shareId commentId:content.commentId releaseUserId:share.releaseUserId sendUserId:content.sendUserId sendUserName:content.sendUserName receiveUserId:M_STOREVALUE(content.receiveUserId) receiveUserName:M_STOREVALUE(content.receiveUserName) content:content.content type:content.commentType successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                    
                    if ([responseObject[@"result"] isEqualToString:@"success"]) {
                        [[[CShareCommentMgr alloc]init] updateCommentWithCommentId:[NSString stringWithFormat:@"%@",responseObject[@"id"]]
                                                                              date:[NSString stringWithFormat:@"%@",responseObject[@"date"]]];
                        [USER_DEFAULT setBool:YES forKey:@"sendOK"];
                        [USER_DEFAULT synchronize];
                    }
                    
                    
                } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
                }];
                
            }];
        }
        
    }
  
}

- (void)checkMessage
{
    
        NSMutableArray *arrayM = [NSMutableArray array];
        [self.safeDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, XMPPMessage *obj, BOOL * stop) {
            NSString *timeStamp = [UIUtil getCurrentTimeStamp];
            NSString *body = [[obj elementForName:@"body"] stringValue];
            if (!M_ISSTRNULL(body)) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                if (dict) {
                    NSDictionary *subDic = dict[@"messageCommon"];
                    if (subDic) {
                        NSString *MessageId = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"messageId"]];
                        NSString *mesTime = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
                        if (timeStamp.longLongValue - mesTime.longLongValue > 120000) {
                            [arrayM addObject:MessageId];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPFAILEDRECEIVEMESSAGE object:MessageId];
                            });
                        }

                    }
                
                }
  
            }
        }];
        [[[CMessageMgr alloc] init] updateMessageStatuIsSendingToFailedWithArray:arrayM];
        [arrayM enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
            [self.safeDict removeObjectForKey:obj];
        }];

    
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)setupStream
{
    NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
    
    // Setup xmpp stream
    //
    // The XMPPStream is the base class for all activity.
    // Everything else plugs into the xmppStream, such as modules/extensions and delegates.
    
    xmppStream = [[XMPPStream alloc] init];
#if !TARGET_IPHONE_SIMULATOR
    {
        // Want xmpp to run in the background?
        //
        // P.S. - The simulator doesn't support backgrounding yet.
        //        When you try to set the associated property on the simulator, it simply fails.
        //        And when you background an app on the simulator,
        //        it just queues network traffic til the app is foregrounded again.
        //        We are patiently waiting for a fix from Apple.
        //        If you do enableBackgroundingOnSocket on the simulator,
        //        you will simply see an error message from the xmpp stack when it fails to set the property.
        
        xmppStream.enableBackgroundingOnSocket = YES;
    }
#endif

    // Setup reconnect
    
    xmppReconnect = [[XMPPReconnect alloc] init];
    xmppReconnect.autoReconnect = YES;
    [xmppReconnect addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [xmppReconnect activate:xmppStream];
    
    xmppAutoPing = [[XMPPAutoPing alloc] init];
    [xmppAutoPing activate:xmppStream];
    [xmppAutoPing addDelegate:self delegateQueue:  dispatch_get_main_queue()];
    xmppAutoPing.respondsToQueries = YES;
    xmppAutoPing.pingInterval = 120.0f;//ping 间隔时间
    

    
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender
{
//    NSLog(@"xmppAutoPingDidSendPing");
}
- (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender
{
//     NSLog(@"xmppAutoPingDidReceivePong");
}
- (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender
{
//     NSLog(@"xmppAutoPingDidTimeout");
}

- (BOOL)xmppReconnect:(XMPPReconnect *)sender shouldAttemptAutoReconnect:(SCNetworkConnectionFlags)connectionFlags
{
    return YES;
}

- (void)xmppReconnect:(XMPPReconnect *)sender didDetectAccidentalDisconnect:(SCNetworkConnectionFlags)connectionFlags
{
    [self connect];
}

// It's easy to create XML elments to send and to read received XML elements.
// You have the entire NSXMLElement and NSXMLNode API's.
//
// In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
//
// On the iPhone, Apple chose not to include the full NSXML suite.
// No problem - we use the KissXML library as a drop in replacement.
//
// For more information on working with XML elements, see the Wiki article:
// https://github.com/robbiehanson/XMPPFramework/wiki/WorkingWithElements

- (void)goOnline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"]; // type="available" is implicit
//    DDXMLNode *staus = [DDXMLNode elementWithName:@"status" stringValue:@"在线"];
//    DDXMLNode *show = [DDXMLNode elementWithName:@"show" stringValue:@"chat"];
//    [presence addAttributeWithName:@"status" stringValue:@"在线"];
//    [presence addAttributeWithName:@"show" stringValue:@"away"];
//    DDXMLNode *apresence = [DDXMLNode elementWithName:@"presence" children:[NSArray arrayWithObjects:staus,show, nil] attributes:nil];
//    [presence addChild:apresence];
    NSString *domain = [xmppStream.myJID domain];
    
    //Google set their presence priority to 24, so we do the same to be compatible.
    if([domain isEqualToString:@"gmail.com"]
       || [domain isEqualToString:@"gtalk.com"]
       || [domain isEqualToString:@"talk.google.com"])
    {
        NSXMLElement *priority = [NSXMLElement elementWithName:@"priority" stringValue:@"24"];
        [presence addChild:priority];
    }
    
    [[self xmppStream] sendElement:presence];
}

- (void)goOffline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    
    [[self xmppStream] sendElement:presence];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connect/disconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL)connect
{
    if ([xmppStream isAuthenticated]) {
        return YES;
    }
    
//    NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
//    NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];
//    CServerSettingMgr *serverMgr = [[CServerSettingMgr alloc] init];
    CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
//    NSString *localServerAddr = [USER_DEFAULT objectForKey:M_SERVERADDR];
//    NSString *localOpenFirePort = [USER_DEFAULT objectForKey:M_OPENFIREPORT];
    NSString *localServerAddr = serverSetting.OpenFireIP;
    NSInteger openFirePort = serverSetting.OpenFirePort;
//    NSInteger openFirePort = 5222;
    if(M_ISSTRNULL(localServerAddr))
    {
        localServerAddr = [serverSetting IMIp];
    }
    if(openFirePort <= 0)
    {
        openFirePort = 5222;
    }
    
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    NSString *myJID = [NSString stringWithFormat:@"%@@%@", acc.userName,localServerAddr];
    NSString *myPassword = acc.passWord;
    
    
    [xmppStream setHostName:localServerAddr];
    [xmppStream setHostPort:openFirePort];
    //
    // If you don't want to use the Settings view to set the JID,
    // uncomment the section below to hard code a JID and password.
    //
    // myJID = @"user@gmail.com/xmppframework";
    // myPassword = @"";
    
    if (myJID == nil || myPassword == nil) {
        return NO;
    }
    
    [xmppStream setMyJID:[XMPPJID jidWithString:myJID resource:@"app"]];
    passWord = myPassword;
    
    NSError *error = nil;
    if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
//                                                            message:@"See console for error details." 
//                                                           delegate:nil 
//                                                  cancelButtonTitle:@"Ok" 
//                                                  otherButtonTitles:nil];
//        [alertView show];
//        
//        DDLogError(@"Error connecting: %@", error);
        
        return NO;
    }
    
    return YES;
}


-(BOOL)connect:(NSString *)user password:(NSString *)password serverIp:(NSString *)serverIp  serverPort:(NSInteger)serverPort
{
    if ([xmppStream isAuthenticated]) {
        return YES;
    }
    
    NSString *myJID = [NSString stringWithFormat:@"%@@%@", user, serverIp];
    NSString *myPassword = password;
    
    //
    // If you don't want to use the Settings view to set the JID,
    // uncomment the section below to hard code a JID and password.
    //
    // myJID = @"user@gmail.com/xmppframework";
    // myPassword = @"";
    
    if (myJID == nil || myPassword == nil) {
        return NO;
    }
    
	[xmppStream setHostName:serverIp];
	[xmppStream setHostPort:serverPort];
    [xmppStream setMyJID:[XMPPJID jidWithString:myJID resource:@"app"]];
    
    passWord = myPassword;
    
    NSError *error = nil;
    if (![xmppStream connectWithTimeout:20 error:&error])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
                                                            message:@"See console for error details."
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
        
        DDLogError(@"Error connecting: %@", error);
        
        return NO;
    }
    
    return YES;
}

- (void)disconnect
{
    
    [xmppStream disconnect];
//    [[CXmppRequestMgr shareInstance] quitLoad];
}



- (void)sendElement:(NSXMLElement *)element
{
    if ([element isKindOfClass:[XMPPMessage class]]) {
//        XMPPMessage *mes = (XMPPMessage *)element;
        [self.safeDict setObject:element forKey:[[element attributeForName:@"id"] stringValue]];
//        if ([mes isGroupMessageWithBody] || [mes isChatMessageWithBody]) {
//            
//        }
    }
    
    if(xmppStream)
    {
        [xmppStream sendElement:element];
    }
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    NSString *expectedCertName = [xmppStream.myJID domain];
    if (expectedCertName)
    {
        settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
    }
    
//    if (customCertEvaluation)
//    {
//        settings[GCDAsyncSocketManuallyEvaluateTrust] = @(YES);
//    }
}

/**
 * Allows a delegate to hook into the TLS handshake and manually validate the peer it's connecting to.
 *
 * This is only called if the stream is secured with settings that include:
 * - GCDAsyncSocketManuallyEvaluateTrust == YES
 * That is, if a delegate implements xmppStream:willSecureWithSettings:, and plugs in that key/value pair.
 *
 * Thus this delegate method is forwarding the TLS evaluation callback from the underlying GCDAsyncSocket.
 *
 * Typically the delegate will use SecTrustEvaluate (and related functions) to properly validate the peer.
 *
 * Note from Apple's documentation:
 *   Because [SecTrustEvaluate] might look on the network for certificates in the certificate chain,
 *   [it] might block while attempting network access. You should never call it from your main thread;
 *   call it only from within a function running on a dispatch queue or on a separate thread.
 *
 * This is why this method uses a completionHandler block rather than a normal return value.
 * The idea is that you should be performing SecTrustEvaluate on a background thread.
 * The completionHandler block is thread-safe, and may be invoked from a background queue/thread.
 * It is safe to invoke the completionHandler block even if the socket has been closed.
 *
 * Keep in mind that you can do all kinds of cool stuff here.
 * For example:
 *
 * If your development server is using a self-signed certificate,
 * then you could embed info about the self-signed cert within your app, and use this callback to ensure that
 * you're actually connecting to the expected dev server.
 *
 * Also, you could present certificates that don't pass SecTrustEvaluate to the client.
 * That is, if SecTrustEvaluate comes back with problems, you could invoke the completionHandler with NO,
 * and then ask the client if the cert can be trusted. This is similar to how most browsers act.
 *
 * Generally, only one delegate should implement this method.
 * However, if multiple delegates implement this method, then the first to invoke the completionHandler "wins".
 * And subsequent invocations of the completionHandler are ignored.
 **/
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
 completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    // The delegate method should likely have code similar to this,
    // but will presumably perform some extra security code stuff.
    // For example, allowing a specific self-signed certificate that is known to the app.
    
    dispatch_queue_t bgQueue = self.xmppMgrQueen;
    dispatch_async(bgQueue, ^{
        
        SecTrustResultType result = kSecTrustResultDeny;
        OSStatus status = SecTrustEvaluate(trust, &result);
        
        if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) {
            completionHandler(YES);
        }
        else {
            completionHandler(NO);
        }
    });
}

- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
    
    isXmppConnected = YES;
    
    NSError *error = nil;
    
    if (![[self xmppStream] authenticateWithPassword:passWord error:&error])
    {
        DDLogError(@"Error authenticating: %@", error);
    }
}

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{

    dispatch_sync(self.xmppMgrQueen, ^{
        [[[CPresenceMgr alloc] init] updateAllPresenceIsUnAvailable];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@YES, K_XMPPLOGINSTATUS, @"登录成功!", K_XMPPLOGINERRMSG, nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPLOGINRESULT object:dic];
            [self goOnline];
            [[CXmppRequestMgr shareInstance] getServerTime];
            [[CXmppRequestMgr shareInstance] setToken];
        });

    });
}

- (CMessageModel *)handleMessage:(XMPPMessage *)aMessage
{
    
    CMessageModel *model = nil;
    if ([aMessage isChatMessageWithBody]) {
        
        NSString *body = [[aMessage elementForName:@"body"] stringValue];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSDictionary *subDic = dict[@"messageCommon"];
        
        model = [[CMessageModel alloc] init];
        
        model.MessageContent = [subDic stringForKey:@"body"];
        model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
        model.MineJid = [aMessage.from.bare stringByReplacingOccurrencesOfString:@"pcapp." withString:@""];
        model.FriendJid = [aMessage.to.bare stringByReplacingOccurrencesOfString:@"pcapp." withString:@""];
        model.FileName = [subDic stringForKey:@"fileName"];
        model.Stream = [subDic stringForKey:@"stream"];
        model.MessageId = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"messageId"]];
        model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
        //        model.GroupId = [subDic stringForKey:@"toId"];
        model.MineUserId = [subDic stringForKey:@"fromId"];
        model.FriendUserId = [subDic stringForKey:@"toId"];
        model.FriendUserName = [subDic stringForKey:@"toName"];
        model.MineUserName = [subDic stringForKey:@"fromName"];
        model.MessageSendedStatus = kMessageSending;
        model.SoundPlayStatus = MessageSoundPlayed;
        model.isMineSend = YES;
        model.ReadStatus = YES;
        model.IsShowInmessageList = YES;
        if (model.TimeStamp.length <= 0) {
            model.TimeStamp = [UIUtil getCurrentTimeStamp];
        }
        
        model.MessageType = [subDic stringForKey:@"type"];
        if ([model.MessageType isEqualToString:@"image"]) {
            
            model.Stream = [[NSJSONSerialization JSONObjectWithData:[subDic[@"stream"] dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil] objectForKey:model.FileName];
            
        }
        
    } else if ([aMessage isGroupMessageWithBody]) {
        
        NSString *body = [[aMessage elementForName:@"body"] stringValue];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSDictionary *subDic = dict[@"messageCommon"];
        
        model = [[CMessageModel alloc] init];
        
        model.MessageContent = [subDic stringForKey:@"body"];
        model.MineJid = [aMessage.from.bare stringByReplacingOccurrencesOfString:@"pcapp." withString:@""];
        model.FriendJid = [aMessage.to.bare stringByReplacingOccurrencesOfString:@"broadcast." withString:@""];
        model.FileName = [subDic stringForKey:@"fileName"];
        model.Stream = [subDic stringForKey:@"stream"];
        model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
        model.MessageId = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"messageId"]];
        model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
        if (model.TimeStamp.length <= 0) {
            model.TimeStamp = [UIUtil getCurrentTimeStamp];
        }
        model.GroupId = [subDic stringForKey:@"groupId"];
        model.MineUserId = [subDic stringForKey:@"fromId"];
        model.FriendUserId = [subDic stringForKey:@"toId"];
        model.FriendUserName = [subDic stringForKey:@"toName"];
        model.MineUserName = [subDic stringForKey:@"fromName"];
        model.MessageSendedStatus = kMessageSending;
        model.SoundPlayStatus = MessageSoundPlayed;
        model.isMineSend = YES;
        model.ReadStatus = YES;
        model.IsShowInmessageList = YES;
        model.MessageType = [subDic stringForKey:@"type"];
        if ([model.MessageType isEqualToString:@"image"]) {
            model.Stream = [[NSJSONSerialization JSONObjectWithData:[subDic[@"stream"] dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil] objectForKey:model.FileName];
        }
        
        model.yuLiuZiduan2 = [self.groupMgr loadGroup:model.GroupId].groupType;
        
    }
    
    
    return model;
}
- (void)sendMessageWithMessage:(XMPPMessage *)message
{
    
//    [Messagetype isEqualToString:@"text"] || [Messagetype isEqualToString:@"file"] || [Messagetype isEqualToString:@"image"] || [Messagetype isEqualToString:@"voice"]
    CMessageModel *mesModel = [self handleMessage:message];
    CGroupModel *group = [self.groupMgr loadGroup:mesModel.GroupId];
    CContactModel *contact = [self.contactMgr loadContactWithUserId:mesModel.FriendUserId];
    CContactModel *curContact = [self.contactMgr loadContactWithUserId:mesModel.MineUserId];
    
    if ([mesModel.MessageType isEqualToString:@"text"]) {
        [[CXmppRequestMgr shareInstance] sendMessageWithMessage:mesModel.MessageContent messageId:mesModel.MessageId curUser:curContact member:contact group:group];
    } else if ([mesModel.MessageType isEqualToString:@"voice"]) {
        
        [[CXmppRequestMgr shareInstance] sendVoiceMessageWihtCurUser:curContact messageId:mesModel.MessageId member:contact group:group fileName:mesModel.FileName timeLenth:mesModel.MessageContent.integerValue];
    } else if ([mesModel.MessageType isEqualToString:@"image"]) {
        NSString *imgDataStr = nil;
        if (group) {
            imgDataStr =  [[[ChildHoodService defaultService] groupUploadImagePathWithGroupId:group.GroupId] stringByAppendingPathComponent:mesModel.FileName];
        } else {
            imgDataStr = [[[ChildHoodService defaultService] personalUploadImagePathWithUserId:curContact.UserID] stringByAppendingPathComponent:mesModel.FileName];
        }
        
        [[CXmppRequestMgr shareInstance] sendImageMessage:[UIImage imageWithContentsOfFile:imgDataStr] messageId:mesModel.MessageId index:0 curUser:curContact member:contact group:group fileName:nil];
    } else if ([mesModel.MessageType isEqualToString:@"file"]) {
        CFileModel *fileModel = [[CFileModel alloc] init];
        NSString *fileId;
        NSString *fileName;
        
        if (group) {
            fileId = group.GroupId;
            fileName = [UIUtil getGroupFileNameWithServerFileName:mesModel.FileName];
            
        } else {
            fileName = [UIUtil getFileNameWithServerFileName:mesModel.FileName];
            fileId = mesModel.MineUserId;
        }
        fileModel.FileName = fileName;
        fileModel.serverFileName = mesModel.FileName;
        NSString *localFilePath = nil;
        if (group) {
            localFilePath = [[[ChildHoodService defaultService] groupUpLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:mesModel.FileName];
        } else {
            localFilePath = [[[ChildHoodService defaultService] personalUpLoadFilePathWithUserId:fileId] stringByAppendingPathComponent:mesModel.FileName];
        }
        
        [[CXmppRequestMgr shareInstance] sendFile:fileModel messageId:mesModel.MessageId curUser:curContact member:contact group:group];
    } else {
        
    }

}

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@NO, K_XMPPLOGINSTATUS, @"用户名或密码错误!", K_XMPPLOGINERRMSG, nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPLOGINRESULT object:dic];
        
    });

    
}

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    DDLogVerbose(@"%@: ＋＋＋＋%@", THIS_FILE, THIS_METHOD);
    dispatch_sync(self.xmppMgrQueen, ^{
       [[[CPresenceMgr alloc] init] updateAllPresenceIsUnAvailable];
        CMessageMgr *mesMgr = [[CMessageMgr alloc] init];
        NSArray *array = [mesMgr updateMessageStatuIsSendingToFailed];
        [mesMgr batchUpdateStatuWithIndeList:array];
        for (NSString *messageId in array) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDSENDMESSAGE object:messageId];
            });
        }
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{
       
        if ([xmppStream isDisconnected])
        {
            DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
                //            NSLog(@"%@",error.localizedDescription);
            
            if (error == nil && self.reachability.currentReachabilityStatus != NotReachable) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@NO, K_XMPPLOGINSTATUS, @"服务器异常!", K_XMPPLOGINERRMSG, nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPLOGINRESULT object:dic];
            } else if ([error.localizedDescription isEqualToString:@"Socket closed by remote peer"]) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@NO, K_XMPPLOGINSTATUS, @"Socket closed by remote peer", K_XMPPLOGINERRMSG, nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPLOGINRESULT object:dic];
            } else {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@NO, K_XMPPLOGINSTATUS, @"网络错误!", K_XMPPLOGINERRMSG, nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPLOGINRESULT object:dic];

            }
        }
        
        
    });

    
}


-(int64_t)getRequestId:(NSString *)elementID
{
    if(M_ISSTRNULL(elementID))
    {
        return 0;
    }
    NSString *beginStr = @"requestId";
    
    NSRange range = [elementID rangeOfString:beginStr];
    int64_t requestId = 0;
    if(range.location != NSNotFound && range.location + [beginStr length] < [elementID length])
    {
        NSString *subString = [elementID substringFromIndex:range.location + [beginStr length]];
        requestId = [subString longLongValue];
    }
    
    return requestId;

}

- (void)xmppStream:(XMPPStream *)sender didFailToSendIQ:(XMPPIQ *)iq error:(NSError *)error
{
    
//    NSLog(@"1112312312312");
    dispatch_async(dispatch_get_main_queue(), ^{
       [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDFAILEDRECEIVEIQ object:nil];
        
    });

   
}

- (void)xmppStream:(XMPPStream *)sender didReceiveError:(DDXMLElement *)error
{
//    NSLog(@"3333333333333");
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEERROR object:nil];
        
    });

    
}

- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    
//    NSLog(@"%@",[NSThread currentThread]);
        
        NSString *elementId = [[iq attributeForName:@"id"] stringValue];
        if(M_ISSTRNULL(elementId))
        {
            //        int64_t requestId =  [self getRequestId:elementId];
            //        if(requestId > 0)
            //        {
            //            CRequestModel *requestModel = [[CRequestMgr shareInstance] getRequestModelByRequestId:requestId];
            //            requestModel.CompleteBlcok(nil, requestModel.Data);
            //        }
//            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDFAILEDRECEIVEIQ object:nil];
            return NO;
        }
        //    NSString *iqStr = [[iq attributeForName:@"id"] stringValue];
    
    
        if([iq elementForName:@"recentcontactuser"] || [iq elementForName:@"recentcontactgroup"]
           || [iq elementForName:@"recentusergroup"])
        {
            [self handleContactUser:iq];
        }
        else if([elementId isEqualToString:@"groupListForUser"]) //groupListForUser
        {
            [self handleGroupList:[iq elementForName:@"groupList"]];
        }
        else if([iq elementForName:@"groupProperty"]) //groupProperty
        {
            [self handleGroupInfo:[iq elementForName:@"groupProperty"]];
        }
        else if([elementId isEqualToString:@"GroupUserList"])
        {
            [self handleGroupMembers:iq];
        } else if([elementId isEqualToString:@"userinfomodify"])
        {
            [self handleUserInfoModify:iq];
        }
        else if([elementId isEqualToString:@"personAutograph"])
        {
            [self handleModifyPersionAutograph:iq];
        } else if([elementId isEqualToString:@"changepassword"])
        {
            [self handleChangePassword:iq];
        }
        else if([elementId isEqualToString:@"userdetails"])
        {
            [self handleUserDetails:iq];
        } else if([elementId isEqualToString:@"deptUserTreeJson"])
        {
            [self handleDeptUserTreeJson:iq];
        }
        else if ([elementId isEqualToString:@"otherUserInfoState"])
        {
            [self handleGetOtherUserInfoState:iq];
        }
        else if([elementId isEqualToString:@"getUserIdByUserCode"])
        {
            [self handleGetUserIdByUserCode:iq];
        } else if ([elementId isEqualToString:@"appmsgNoticeSetGet"])
        {
            [self handleappmsgNoticeSetGet:iq];
        } else if ([elementId isEqualToString:@"appmsgNoticeSetSet"])
        {
            [self handleappmsgNoticeSetSet:iq];
        } else if ([elementId isEqualToString:@"getServerDate"])
        {
            [self handleGEtServerDate:iq];
        } else if ([elementId isEqualToString:@"getcompanypresences"]) {
            [self handleGetCompanyPresences:iq];
        } else if ([elementId isEqualToString:@"setToken"]) {
            [self handleSetToken:iq];
        } else if ([elementId isEqualToString:@"contactList"]){
            [self handleGetOftenConactList:iq];
            
        } else if ([elementId isEqualToString:@"contactAdd"]){
            [self  handleAddOftenConactList:iq];
            
        } else if ([elementId isEqualToString:@"contactDelete"]){
            [self handleDeleteOftenConactList:iq];
            
        } else if ([elementId isEqualToString:@"callTelephoneNumber"]) {
            [self handleTelephoneNumber:iq];
        } else if ([elementId isEqualToString:@"discussiongroupcreate"]) {
            [self handleCreateDiscussion:iq];
        } else if ([elementId isEqualToString:@"discussiongroupupdate"]){
            [self handleDiscussiongroupupdate:iq];
        } else if ([elementId isEqualToString:@"discussiongroupcremem"]) {
            [self handleDiscussiongAddMember:iq];
        } else if ([elementId isEqualToString:@"discussiongroupdel"]) {
            [self handleDiscussiongDel:iq];
        } else if ([elementId isEqualToString:@"discussiongroupexitmem"]) {
            [self handleDiscussiongSignOut:iq];
        } else if ([elementId isEqualToString:@"discussiongroupdelmem"]) {
            [self handleDiscussiongDelMem:iq];
        } else if ([elementId isEqualToString:@"getcompanykf"]) {
            [self handleKefuList:iq];
        }




    
        
        return YES;
    
}

- (void)handleDiscussiongDelMem:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
        
        
        NSXMLElement *groupMembers = [iq elementForName:@"talkOverGroupProperty"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupdelmem"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict = (NSDictionary *)mbers;
                NSString *disId = [dict stringForKey:@"groupId"];
                CGroupModel *group = [mgr loadGroup:disId];
                if (group) {
                    group.UserNum = [dict integerForKey:@"groupCount"];
                    [mgr updateGroup:group];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDELDISCUSSMEM object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });
            
            
        }
        
    });

}

- (void)handleDiscussiongSignOut:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
        NSXMLElement *groupMembers = [iq elementForName:@"result"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupexitmem"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            CMessageMgr *mesMgr = [[CMessageMgr alloc] init];
            CMessageDraftMgr *draftMgr = [[CMessageDraftMgr alloc] init];
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                
                NSDictionary *dict = (NSDictionary *)mbers;
                BOOL status = [dict boolForKey:@"status"];
                if (status) {
                    NSString *disId = [dict stringForKey:@"groupId"];
                    [mgr delGroupWithGroupId:disId];
                    [mesMgr delGroupMessageWithGroupId:disId];
                    [draftMgr delMessageDraftWithGroupId:disId];
                    
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPSIGNOUTDISCUSSION object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });
            
            
        }
        
    });
    
}

- (void)handleDiscussiongDel:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
        
//        NSLog(@"%@ === %@",[iq description],iq.fromStr);
        NSXMLElement *groupMembers = [iq elementForName:@"result"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupdel"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                
                NSDictionary *dict = (NSDictionary *)mbers;
                BOOL status = [dict boolForKey:@"status"];
                if (status) {
                    NSString *disId = [dict stringForKey:@"groupId"];
                    [mgr delGroupWithGroupId:disId];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
                
            });
            
            
        }
        
    });
    
}

- (void)handleDiscussiongAddMember:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
        
//            NSLog(@"%@ === %@",[iq description],iq.fromStr);
        NSXMLElement *groupMembers = [iq elementForName:@"talkOverGroupProperty"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupcremem"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict = (NSDictionary *)mbers;
                NSString *disId = [dict stringForKey:@"groupId"];
                CGroupModel *group = [mgr loadGroup:disId];
                if (group) {
                    group.UserNum = [dict integerForKey:@"groupCount"];
                    [mgr updateGroup:group];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPADDDISCUSSIONMEM object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });
            
            
        }
        
    });

}

- (void)handleDiscussiongroupupdate:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
        
        NSXMLElement *groupMembers = [iq elementForName:@"result"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupupdate"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                
                NSDictionary *dict = (NSDictionary *)mbers;
                BOOL status = [dict boolForKey:@"status"];
                if (status) {
                    NSString *disId = [dict stringForKey:@"groupId"];
                    CGroupModel *group = [mgr loadGroup:disId];
                    if (group) {
                        group.isShow = [dict integerForKey:@"isHidden"];
                        group.GroupName = [dict stringForKey:@"groupName"];
                        group.GroupNotice = [dict stringForKey:@"groupNotice"];
                        group.GroupIntroduction = [dict stringForKey:@"groupIntroduction"];
                        [mgr updateGroup:group];
                    }
                }
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEDISCUSSIONINFO object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });
            
            
        }
        
    });

    
}
- (void)handleCreateDiscussion:(XMPPIQ *)iq
{
    __block NSString *groupId;
    dispatch_async(self.xmppMgrQueen, ^{
        
//        NSLog(@"%@",iq.description);
        NSXMLElement *groupMembers = [iq elementForName:@"talkOverGroupProperty"];
        if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:discussiongroupcreate"])
        {
            id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            CContactModel *curModel = [[[CContactMgr alloc] init] loadCurContact];
            CGroupMgr *mgr = [[CGroupMgr alloc] init];
            if ([mbers isKindOfClass:[NSDictionary class]]) {
                
                NSDictionary *dict = (NSDictionary *)mbers;
                CGroupModel *group = [[CGroupModel alloc] init];
                group.isShow = [dict boolForKey:@"isHidden"];
                group.groupType = [dict intForKey:@"type"];
                group.GroupName = [dict stringForKey:@"groupName"];
                group.GroupId = [dict stringForKey:@"groupId"];
                group.GroupIntroduction = [dict stringForKey:@"groupIntroduction"];
                group.GroupNotice = [dict stringForKey:@"groupNotice"];
                group.GroupCreateDate = [dict stringForKey:@"createDate"];
                if (M_ISSTRNULL(group.GroupCreateDate)) {
                    group.GroupCreateDate = [UIUtil getCurrentTimeStamp];
                }
                group.OwnerId = curModel.UserID;
                [mgr insertGroup:group];
                groupId = group.GroupId;
                //bug 重复名字 讨论组 解决
                [[CXmppRequestMgr shareInstance] addDiscussMemberwithGroup:group members:[[[CContactMgr alloc] init] loadAllSelectedContact] curUser:nil];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
              //bug 9270 fixed by lixu
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPCREATEDISCUSSION object:nil userInfo:@{@"groupid":groupId}];
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });
            
            
        }
        
    });
}

- (void)handleTelephoneNumber:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
     NSXMLElement *ele = [iq elementForName:@"getctnumber"];
    CCompanyMgr *comMgr = [[CCompanyMgr alloc] init];
    id array = [NSJSONSerialization JSONObjectWithData:[[ele stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    if ([array isKindOfClass:[NSArray class]]) {
        [comMgr delAllCompany];
        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            CCompany *company = [[CCompany alloc] init];
            company.compCode = [dict objectForKey:@"compCode"];
           id callcenterTelephoneArray = [dict objectForKey:@"callcenterTelephone"];
            if ([callcenterTelephoneArray isKindOfClass:[NSArray class]]) {
                [callcenterTelephoneArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                    if (idx == 0) {
                        company.callcenterTelephone = [obj objectForKey:@"outLine"];
                        *stop = YES;
                    }
                }];
            } else if ([callcenterTelephoneArray isKindOfClass:[NSString class]]) {
                company.callcenterTelephone = [dict objectForKey:@"callcenterTelephone"];
            }
            [arrayM addObject:company];
        }
        [comMgr batchInsertCompany:arrayM];
    }
    });
}
- (void)handleGetOftenConactList:(XMPPIQ *)iq
{
    
//    NSLog(@"1");
    dispatch_async(self.xmppMgrQueen, ^{
    CRecentlyContactMgr *mgr = [[CRecentlyContactMgr alloc] init];
    [mgr delAllRecentlyContacts];
    NSXMLElement *ele = [iq elementForName:@"contact"];
    if (ele == nil) {
        return;
    }
//    NSXMLElement *sub = [ele elementForName:@"contactIds"];
//    if (sub == nil) {
//        return;
//    }
    id preArray = [NSJSONSerialization JSONObjectWithData:[[ele stringValue]dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:5];
    if ([preArray isKindOfClass:[NSArray class]]) {
        for (NSDictionary *dict in preArray) {
            CRecentlyContactModel *model = [[CRecentlyContactModel alloc] init];
            model.userId = [NSString stringWithFormat:@"%@",[dict objectForKey:@"id"]];
            [arrayM addObject:model];
            model = nil;
        }
        
    }
    
        [mgr batchInsertRecentlyContact:arrayM];
    });

}

- (void)handleAddOftenConactList:(XMPPIQ *)iq
{
    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDGERECENTLYLIST object:nil];
}
- (void)handleDeleteOftenConactList:(XMPPIQ *)iq
{
    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDGERECENTLYLIST object:nil];
}


- (void)handleSetToken:(XMPPIQ *)iq
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPSETTOKEN object:nil];
}
- (void)handleGetCompanyPresences:(XMPPIQ *)iq
{
//    NSXMLElement *ele = [iq elementForName:@"result"];
//    if (ele == nil) return;
//    NSString *result = [[ele elementForName:@"resultinfo"] stringValue];
//    if ([result isEqualToString:@"1"]) {
//        NSXMLElement *presences = [ele elementForName:@"presences"];
//        if (presences == nil) return;
//        CContactMgr *mgr = [[CContactMgr alloc] init];
//        [mgr updateAllContactStatus];
//        id preArray = [NSJSONSerialization JSONObjectWithData:[[presences stringValue]dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
//        if ([preArray isKindOfClass:[NSArray class]]) {
//            for (NSDictionary *dict in preArray) {
//                XMPPJID *jid = [XMPPJID jidWithString:[dict objectForKey:@"jid"]];
//                CContactModel *contact = [mgr loadContactWithUserCode:jid.user];
//                contact.IsAvailable = [NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]];
////                if (![contact.IsAvailable isEqualToString:@"离线"]) {
////                    
////                }
//                [mgr updateContact:contact];
//            }
//            
//        }
//    }
}

- (void)handleGEtServerDate:(XMPPIQ *)iq
{
        if ([[[iq attributeForName:@"type"] stringValue] isEqualToString:@"failed"]) {
            return;
        }
        NSXMLElement *ele = [iq elementForName:@"serverDate"];
        if (ele) {
            NSString *timeStamp;
                id obj = [NSJSONSerialization JSONObjectWithData:[ele.stringValue dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            if ([obj isKindOfClass:[NSDictionary class]]) {
                timeStamp = [NSString stringWithFormat:@"%@", [obj objectForKey:@"serverDate"]];
                if (timeStamp.longLongValue <= 0) {
                    return;
                }
                NSTimeInterval ti = [[NSDate date] timeIntervalSince1970] * 1000;
                NSTimeInterval timeGap = timeStamp.doubleValue - ti;
                [USER_DEFAULT  setObject:[NSString stringWithFormat:@"%f",timeGap] forKey:SERVER_TIME_SYS];
                [USER_DEFAULT setObject:[NSString stringWithFormat:@"%@",[obj objectForKey:@"uploadFileSizeLimit"]] forKey:FILEMAXSIZE];
                [USER_DEFAULT synchronize];
            }
            
        }
}

- (void)handleGetUserIdByUserCode:(XMPPIQ *)iq
{
    NSXMLElement *ele = [iq elementForName:@"getUserIdByUserCode"];
    if (ele) {
        NSXMLElement *eleUserId = [ele elementForName:@"userId"];
        CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
        if (eleUserId) {
            id idStr = [NSJSONSerialization JSONObjectWithData:[[eleUserId stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            acc.userId = idStr[@"userId"];
            [[CFolderMgr shareInstance].accMgr updateAccount:acc];
            [[CXmppRequestMgr shareInstance] getKefuList];
            [[CXmppRequestMgr shareInstance] getGroupListWithUserId:acc.userId];
            [[CXmppRequestMgr shareInstance] loadShareData];
            [[CXmppRequestMgr shareInstance] getMineAttentionWithsuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSString *result = responseObject[@"result"];
                
                if ([result isEqualToString:@"success"]) {
                    
                    CAttentionMgr *attenMgr = [[CAttentionMgr alloc] init];
                    [attenMgr delAllAttentionContacts];
                    
                    NSMutableArray *arrayM = [NSMutableArray array];
                    NSString *meAttentionId = responseObject[@"meAttentionId"];
                    NSArray *meAttentionIdArray = [meAttentionId componentsSeparatedByString:@","];
                    [meAttentionIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                        CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                        attention.userId = obj;
                        attention.isAttentionMe = NO;
                        [arrayM addObject:attention];
                    }];
                    
                    NSString *attentionMeId = responseObject[@"attentionMeId"];
                    NSArray *attentionMeIdArray = [attentionMeId componentsSeparatedByString:@","];
                    [attentionMeIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                        CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                        attention.userId = obj;
                        attention.isAttentionMe = YES;
                        [arrayM addObject:attention];
                    }];
                    [attenMgr batchInsertAttentionContact:arrayM];
                } else {
                    
                }
                
            } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                
            }];

            [[CXmppRequestMgr shareInstance] getOtherUserUpdateInfo:acc.userId];
            [[CXmppRequestMgr shareInstance] getOftenContact];
            [[CXmppRequestMgr shareInstance] getUpdateInfo];
            [[CXmppRequestMgr shareInstance] getCallCenterTelePhoneNumberWithUserId:acc.userId];
        }
    }
    
    
}

- (void)handleappmsgNoticeSetGet:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
    NSXMLElement *ele = [iq elementForName:@"getuserinfo"];
    CUserSettingMgr *setMgr = [[CUserSettingMgr alloc] init];
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    if (ele) {
        NSXMLElement *msgSet = [ele elementForName:@"msgNoticeSetSet"];
        if (msgSet) {
            id setStr = [NSJSONSerialization JSONObjectWithData:[[msgSet stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            
            CUserSettingModel *model = [[CUserSettingModel alloc] init];
            model.userCode = acc.userName;
            model.BothOnline = [setStr boolForKey:@"sameOnline"];
            
//            NSLog(@"%d   ====hehe      %@",[setStr boolForKey:@"sameOnline"],[setStr stringForKey:@"sameOnline"]);
            model.Voice = [setStr boolForKey:@"sound"];
            model.Shake = [setStr  boolForKey:@"vibration"];
            model.Disturb = [setStr boolForKey:@"noDisturb"];
            model.StartDate = [setStr objectForKey:@"noDisturbStart"];
            model.EndDate = [setStr objectForKey:@"noDisturbEnd"];
            model.yuLiuZiduan3 = @"按部门显示";
            [setMgr insetUserWithSetting:model];
        }
    }
    });
}

- (void)handleappmsgNoticeSetSet:(XMPPIQ *)iq
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPSETNOTICESETTING object:nil];
        
    });

    
}


- (void)handleGetOtherUserInfoState:(XMPPIQ *)iq
{
   
    dispatch_async(self.xmppMgrQueen, ^{
    NSXMLElement *ele = [iq elementForName:@"otherUserinfoState"];
    if (ele) {
        NSXMLElement *eleUserId = [ele elementForName:@"userinfoState"];
        if (eleUserId) {
            id jsonStr = [NSJSONSerialization JSONObjectWithData:[[eleUserId stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            if ([jsonStr isKindOfClass:[NSDictionary class]]) {
                
                id deptJson = [jsonStr objectForKey:@"dept"];
                if ([deptJson isKindOfClass:[NSArray class]]) {
                    CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
                    NSArray *depJsonArray = (NSArray*)deptJson;
                    for (NSDictionary *depdict in depJsonArray) {
                        NSString *depId = [depdict objectForKey:@"id"];
                        
                        if (!M_ISSTRNULL(depId)) {
                            
                            CDepartmentModel *departModel = [depMgr loadDepartment:depId];
                            if (departModel) {
                                departModel.DEPTID = depId;
                                departModel.UserNum = [[depdict objectForKey:@"userNum"] intValue];
                                departModel.Sequence = [[depdict objectForKey:@"sequence"] intValue];
                                departModel.DepartName = [depdict objectForKey:@"name"];
                                departModel.DeptFatherID = [depdict objectForKey:@"pid"];
                                departModel.IsDel = [[depdict objectForKey:@"isDel"] boolValue];
                                NSNumber *infoState = [depdict objectForKey:@"infoState"];
                                departModel.InfoState = [NSString stringWithFormat:@"%lld", [infoState longLongValue]];
                                [depMgr updateDepartment:departModel];
                            } else {
                                departModel = [[CDepartmentModel alloc] init];
                                departModel.DEPTID = depId;
                                departModel.UserNum = [[depdict objectForKey:@"userNum"] intValue];
                                departModel.Sequence = [[depdict objectForKey:@"sequence"] intValue];
                                departModel.DepartName = [depdict objectForKey:@"name"];
                                departModel.DeptFatherID = [depdict objectForKey:@"pid"];
                                departModel.IsDel = [[depdict objectForKey:@"isDel"] boolValue];
                                NSNumber *infoState = [depdict objectForKey:@"infoState"];
                                departModel.InfoState = [NSString stringWithFormat:@"%lld", [infoState longLongValue]];
                                [depMgr insertDepartment:departModel];
                            }
                        }
                        
                    }
                    
                }
                id infoJson = [jsonStr objectForKey:@"info"];
                if ([infoJson isKindOfClass:[NSArray class]]) {
                    CContactMgr *contMgr = [[CContactMgr alloc] init];
                    for (NSDictionary *infoDict in infoJson) {
                        NSString *userid = [infoDict objectForKey:@"id"];
                        if (!M_ISSTRNULL(userid)) {
                            
                            CContactModel *contactModel = [contMgr loadContactWithUserId:userid];
                            if (contactModel) {
                                contactModel.Position = [infoDict objectForKey:@"position"];
                                contactModel.EXtenSion = [infoDict objectForKey:@"extension"];
                                contactModel.UserID = [infoDict objectForKey:@"id"];
                                [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contactModel.UserID]];
                                [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contactModel.UserID] fromDisk:YES];
                                contactModel.isDel = [[infoDict objectForKey:@"isDel"] boolValue];
                                contactModel.Autograph = [infoDict objectForKey:@"autograph"];
                                contactModel.UserCode = [infoDict objectForKey:@"userCode"];
                                contactModel.UserName = [infoDict objectForKey:@"realName"];
                                contactModel.DEPTID = [infoDict objectForKey:@"deptId"];
                                contactModel.RoleID = [infoDict objectForKey:@"roleId"];
                                contactModel.SEX = [infoDict objectForKey:@"sex"];
                                contactModel.MobileTelephone = [infoDict objectForKey:@"mobilePhone"];
                                contactModel.Email = [infoDict objectForKey:@"email"];
                                contactModel.birthDay = [infoDict objectForKey:@"birthday"];
                                contactModel.address = [infoDict objectForKey:@"address"];
                                contactModel.Telephone = [infoDict objectForKey:@"telephone"];
                                contactModel.HeadPortrait = [infoDict objectForKey:@"HeadPortrait"];
                                contactModel.DEPNAME = [infoDict objectForKey:@"dept"];
                                contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                                contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:contactModel.UserName] lowercaseString];
                                contactModel.compCode = [NSString stringWithFormat:@"%@",[infoDict objectForKey:@"compCode"]];
                                
                                [contMgr updateContact:contactModel];
                                
                            } else {
                                contactModel = [[CContactModel alloc] init];
                                
                                contactModel.Position = [infoDict objectForKey:@"position"];
                                contactModel.EXtenSion = [infoDict objectForKey:@"extension"];
                                contactModel.UserID = [infoDict objectForKey:@"id"];
                                contactModel.isDel = [[infoDict objectForKey:@"isDel"] boolValue];
                                contactModel.Autograph = [infoDict objectForKey:@"autograph"];
                                contactModel.UserCode = [infoDict objectForKey:@"userCode"];
                                contactModel.UserName = [infoDict objectForKey:@"realName"];
                                contactModel.DEPTID = [infoDict objectForKey:@"deptId"];
                                contactModel.RoleID = [infoDict objectForKey:@"roleId"];
                                contactModel.SEX = [infoDict objectForKey:@"sex"];
                                contactModel.MobileTelephone = [infoDict objectForKey:@"mobilePhone"];
                                contactModel.Email = [infoDict objectForKey:@"email"];
                                contactModel.birthDay = [infoDict objectForKey:@"birthday"];
                                contactModel.address = [infoDict objectForKey:@"address"];
                                contactModel.Telephone = [infoDict objectForKey:@"telephone"];
                                contactModel.HeadPortrait = [infoDict objectForKey:@"HeadPortrait"];
                                contactModel.DEPNAME = [infoDict objectForKey:@"dept"];
                                contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                                contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:contactModel.UserName] lowercaseString];
                                contactModel.compCode = [NSString stringWithFormat:@"%@",[infoDict objectForKey:@"compCode"]];
                                contactModel.IsAvailable = @"离线";
                                [contMgr insetContact:contactModel];
                            }
                        }

                    }
                }
                
                id groupJson = [jsonStr objectForKey:@"group"];
                if ([groupJson isKindOfClass:[NSArray class]]) {
                    CGroupMgr *groupMgr = [[CGroupMgr alloc] init];
                    for (NSDictionary *groupDict in groupJson) {
                        NSString *groupId = [groupDict objectForKey:@"id"];
                        if (!M_ISSTRNULL(groupId)) {
                            CGroupModel *groupModel = [[CGroupModel alloc] init];
                            groupModel.GroupId = groupId;
                            groupModel.GroupName = [groupDict stringForKey:@"name"];
                            groupModel.GroupIntroduction = [groupDict stringForKey:@"introduction"];
                            groupModel.OwnerId = [groupDict stringForKey:@"ownerId"];
                            groupModel.UserNum = [groupDict integerForKey:@"userCount"];
                            groupModel.OwnerName = [groupDict stringForKey:@"owner"];
                            groupModel.GroupNotice = [groupDict stringForKey:@"notice"];
                            groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                            groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[groupDict stringForKey:@"name"]] lowercaseString];
                            groupModel.IsDel = [groupDict boolForKey:@"isDel"];
                            [groupMgr insertGroup:groupModel];
                        }
                    }
                }

                id imgJson = [jsonStr objectForKey:@"img"];
                if ([imgJson isKindOfClass:[NSString class]]) {
                   
                    NSArray *array = [imgJson componentsSeparatedByString:@","];
                    for (NSString *userId in array) {
                        [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:userId]];
                        [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:userId] fromDisk:YES];
                    }
                }
                
                
                [USER_DEFAULT setObject:[jsonStr objectForKey:@"timestamp"] forKey:infoTimeStamp];
                [USER_DEFAULT setBool:YES forKey:isOtherContactCompleted];
                [USER_DEFAULT synchronize];

            }
            
        }
    }
         [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
    });

    
}

//deptUserTreeJson
-(BOOL)handleDeptUserTreeJson:(XMPPIQ *)iq
{
    
    dispatch_async(self.xmppMgrQueen, ^{
    CContactMgr *contactMgr = [[CContactMgr alloc] init];
    NSXMLElement *deptNode = [iq elementForName:@"OrganizationTree"];
    if(deptNode != nil)
    {
        NSString *str = [deptNode stringValue];
        NSError *error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
        id allUser = [jsonObject objectForKey:@"allUser"];
        [USER_DEFAULT setObject:[jsonObject objectForKey:@"timestamp"] forKey:infoTimeStamp];
         [USER_DEFAULT synchronize];
        if([allUser isKindOfClass:[NSArray class]])
        {
            
            [contactMgr delAllContact];
            NSMutableArray *contArray = [NSMutableArray arrayWithCapacity:5];
            
            [allUser enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
                
                CContactModel *contactModel = [[CContactModel alloc] init];
                contactModel.Position = [index objectForKey:@"position"];
                contactModel.EXtenSion = [index objectForKey:@"extension"];
                contactModel.UserID = [index objectForKey:@"id"];
                contactModel.isDel = [[index objectForKey:@"isDel"] boolValue];
                contactModel.Autograph = [index objectForKey:@"autograph"];
                contactModel.UserCode = [index objectForKey:@"userCode"];
                contactModel.UserName = [index objectForKey:@"realName"];
                contactModel.DEPTID = [index objectForKey:@"deptId"];
                contactModel.RoleID = [index objectForKey:@"roleId"];
                contactModel.SEX = [index objectForKey:@"sex"];
                contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
                contactModel.Email = [index objectForKey:@"email"];
                contactModel.birthDay = [index objectForKey:@"birthday"];
                contactModel.address = [index objectForKey:@"address"];
                contactModel.Telephone = [index objectForKey:@"telephone"];
                contactModel.HeadPortrait = [index objectForKey:@"HeadPortrait"];
                contactModel.DEPNAME = [index objectForKey:@"dept"];
                contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"realName"]] lowercaseString];
                contactModel.compCode = [NSString stringWithFormat:@"%@",[index objectForKey:@"compCode"]];
                contactModel.IsAvailable = @"离线";
                [contArray addObject:contactModel];
                contactModel = nil;
            }];
        
            [contactMgr batchInsertContact:contArray];
        }
        
        id allDept = [jsonObject objectForKey:@"alldept"];
//        NSLog(@"allDept:%@", allDept);
        if([allDept isKindOfClass:[NSArray class]])
        {
            CDepartmentMgr *departMgr = [[CDepartmentMgr alloc] init];
            NSMutableArray *depArray = [NSMutableArray arrayWithCapacity:5];
            [departMgr delAllDepartment];            
            [allDept enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
        
                CDepartmentModel *departModel = [[CDepartmentModel alloc] init];
                departModel.DEPTID = [index objectForKey:@"id"];
                departModel.UserNum = [[index objectForKey:@"userNum"] intValue];
                departModel.Sequence = [[index objectForKey:@"sequence"] intValue];
                departModel.DepartName = [index objectForKey:@"name"];
                departModel.DeptFatherID = [index objectForKey:@"pid"];
                departModel.IsDel = [[index objectForKey:@"isDel"] boolValue];
                NSNumber *infoState = [index objectForKey:@"infoState"];
                departModel.InfoState = [NSString stringWithFormat:@"%lld", [infoState longLongValue]];
                [depArray addObject:departModel];
                departModel = nil;
            }];
            
            [departMgr batchInsertDepartment:depArray];
        }
        
    
    }
    
    [[CXmppRequestMgr shareInstance] getDelAndDisableUserWithSuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
         dispatch_async(self.xmppMgrQueen, ^{
        if ([responseObject isKindOfClass:[NSArray class]]) {
            [contactMgr delAllDelContact];
            NSMutableArray *contArray = [NSMutableArray array];
            [responseObject enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
                CContactModel *contactModel = [[CContactModel alloc] init];
                contactModel.Position = [index objectForKey:@"position"];
                contactModel.EXtenSion = [index objectForKey:@"extension"];
                contactModel.UserID = [index objectForKey:@"id"];
                contactModel.isDel = [[index objectForKey:@"isDel"] boolValue];
                contactModel.Autograph = [index objectForKey:@"autograph"];
                contactModel.UserCode = [index objectForKey:@"userCode"];
                contactModel.UserName = [index objectForKey:@"realName"];
                contactModel.DEPTID = [index objectForKey:@"deptId"];
                contactModel.RoleID = [index objectForKey:@"roleId"];
                contactModel.SEX = [index objectForKey:@"sex"];
                contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
                contactModel.Email = [index objectForKey:@"email"];
                contactModel.birthDay = [index objectForKey:@"birthday"];
                contactModel.address = [index objectForKey:@"address"];
                contactModel.Telephone = [index objectForKey:@"telephone"];
                contactModel.HeadPortrait = [index objectForKey:@"HeadPortrait"];
                contactModel.DEPNAME = [index objectForKey:@"dept"];
                contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"realName"]] lowercaseString];
                contactModel.compCode = [NSString stringWithFormat:@"%@",[index objectForKey:@"compCode"]];
                contactModel.IsAvailable = @"离线";
                [contArray addObject:contactModel];
                contactModel = nil;
                
            }];
            [contactMgr batchInsertContact:contArray];
        }
         });
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
        CContactModel *curModel = [contactMgr loadCurContact];
        CAccountModel *curaccount = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
        curaccount.userId = curModel.UserID;
        [[CFolderMgr shareInstance].accMgr updateAccount:curaccount];
        [[CXmppRequestMgr shareInstance] getUserSettingInfo];
        [[CXmppRequestMgr shareInstance] getUpdateInfo];
        [[CXmppRequestMgr shareInstance] getOtherUserUpdateInfo:curModel.UserID];
        [[CXmppRequestMgr shareInstance] loadShareData];
        [[CXmppRequestMgr shareInstance] getGroupListWithUserId:curModel.UserID];
        [[CXmppRequestMgr shareInstance] getMineAttentionWithsuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *result = responseObject[@"result"];
        
        if ([result isEqualToString:@"success"]) {
            
            CAttentionMgr *attenMgr = [[CAttentionMgr alloc] init];
            [attenMgr delAllAttentionContacts];
            
            NSMutableArray *arrayM = [NSMutableArray array];
            NSString *meAttentionId = responseObject[@"meAttentionId"];
            NSArray *meAttentionIdArray = [meAttentionId componentsSeparatedByString:@","];
            [meAttentionIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                attention.userId = obj;
                attention.isAttentionMe = NO;
                [arrayM addObject:attention];
            }];
            
            NSString *attentionMeId = responseObject[@"attentionMeId"];
            NSArray *attentionMeIdArray = [attentionMeId componentsSeparatedByString:@","];
            [attentionMeIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                attention.userId = obj;
                attention.isAttentionMe = YES;
                [arrayM addObject:attention];
            }];
            [attenMgr batchInsertAttentionContact:arrayM];
        } else {
            
        }
        
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    [[CXmppRequestMgr shareInstance] getKefuList];
    [[CXmppRequestMgr shareInstance] getOftenContact];
    [[CXmppRequestMgr shareInstance] getCallCenterTelePhoneNumberWithUserId:curModel.UserID];
    [USER_DEFAULT setBool:YES forKey:isContactCompleted];
    [USER_DEFAULT synchronize];
   });
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDGETDEPTREE object:nil];
        });

    return YES;
}




-(BOOL)handleUserDetails:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
    NSXMLElement *groupMembers = [iq elementForName:@"getuserinfo"];
       if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:userdetails"])
    {
        NSArray *children = [groupMembers children];
        for(NSXMLElement *ele in children)
        {
            if([[ele name] isEqualToString:@"userInfo"])
            {
                NSString *str = [ele stringValue];
                id jsonObject = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];

                if ([jsonObject isKindOfClass:[NSArray class]]) {
                    CContactMgr *conMgr = [[CContactMgr alloc] init];
                    for (NSDictionary *index in jsonObject) {
                        
                        CContactModel *contactModel = [conMgr loadContactWithUserId:[index objectForKey:@"id"]];
                        contactModel.DEPTID = [index objectForKey:@"deptId"];
                        contactModel.UserName = [index objectForKey:@"realName"];
                        contactModel.EXtenSion = [index objectForKey:@"extension"];
                        contactModel.Autograph = [index objectForKey:@"autograph"];
                        contactModel.Position = [index objectForKey:@"position"];
                        contactModel.RoleID = [index objectForKey:@"roleId"];
                        contactModel.Telephone = [index objectForKey:@"telephone"];
                        contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
                        contactModel.Email = [index objectForKey:@"email"];
                        contactModel.HeadPortrait = [index objectForKey:@"HeadPortrait"];
                        contactModel.DEPNAME = [index objectForKey:@"dept"];
                        contactModel.SEX = [index objectForKey:@"sex"];
                        contactModel.address = [index objectForKey:@"address"];
                        contactModel.birthDay = [index objectForKey:@"birthday"];
                        [conMgr updateContact:contactModel];
                        contactModel = nil;
                    }
                }
                }
        }
    }
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPGETUSETINFO object:nil];
            
        });

    });
   
   
    return YES;
}

-(BOOL)handleGroupUpdate:(XMPPIQ *)iq
{
    NSArray *array = [iq children];
    if([array count] > 0)
    {
//        NSXMLElement *firstChild = [array objectAtIndex:0];
//        NSLog(@"type:%@, result:%@", [iq type], [firstChild xmlns]);
    }
    return YES;
}

-(BOOL)handleDelGroup:(XMPPIQ *)iq
{
    NSArray *array = [iq children];
    if([array count] > 0)
    {
//        NSXMLElement *firstChild = [array objectAtIndex:0];
//        NSLog(@"type:%@, result:%@", [iq type], [firstChild xmlns]);
    }
    return YES;
}



-(BOOL)handleChangePassword:(XMPPIQ *)iq //changepassword
{
    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEPASSWORD object:nil userInfo:@{@"iq":iq}];
    NSArray *array = [iq children];
    if([array count] > 0)
    {
//        NSXMLElement *firstChild = [array objectAtIndex:0];
//        NSLog(@"type:%@, result:%@ %@", [iq type], [firstChild xmlns], [firstChild name]);
    }
    return YES;
}
-(BOOL)handleModifyPersionAutograph:(XMPPIQ *)iq
{

    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATESIGNATURE object:nil userInfo:@{@"iq":iq}];
    NSArray *array = [iq children];
    if([array count] > 0)
    {
//        NSXMLElement *firstChild = [array objectAtIndex:0];
//        NSLog(@"type:%@, result:%@", [iq type], [firstChild xmlns]);
    }
    return YES;
}


-(BOOL)handleUserInfoModify:(XMPPIQ *)iq
{
    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPMODIFYINFO object:nil userInfo:@{@"iq":iq}];
    
    return YES;
}

-(BOOL)handleGroupDelMember:(XMPPIQ *)iq
{

//    NSArray *array = [iq children];
//    if([array count] > 0)
//    {
//        NSXMLElement *firstChild = [array objectAtIndex:0];
////        NSLog(@"type:%@, result:%@", [iq type], [firstChild xmlns]);
//    }
    return YES;
}


-(BOOL)handleGroupMembers:(XMPPIQ *)iq
{
    dispatch_async(self.xmppMgrQueen, ^{
        
    NSXMLElement *groupMembers = [iq elementForName:@"groupUserList"];
        if (groupMembers) {
            if([[groupMembers xmlns] isEqualToString:@"com:im:wanzhao:GroupUserList"])
            {
                id mbers = [NSJSONSerialization JSONObjectWithData:[[groupMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
                
                CGroupMemberMgr *mgr = [[CGroupMemberMgr alloc] init];
                if ([mbers isKindOfClass:[NSArray class]]) {
                    NSString *groupId = nil;
                    NSMutableArray *arrayM = [NSMutableArray array];
                    for (NSDictionary *dict in mbers) {
                        CGroupMemberModel *contact = [[CGroupMemberModel alloc] init];
                        contact.UserId = [dict objectForKey:@"id"];
                        contact.GroupID = [dict objectForKey:@"groupId"];
                        groupId = contact.GroupID;
                        contact.Available = [dict boolForKey:@"available"];
                        contact.UserCode = [dict stringForKey:@"userCode"];
                        contact.LastTime = [NSString stringWithFormat:@"%@",[dict objectForKey:@"lastTime"]];
                        [arrayM addObject:contact];
                        //                [mgr insetGroupMember:contact];
                    }
                    [mgr delAllGroupMembeWithGroupId:groupId];
                    [mgr batchInsertGroupMember:arrayM];
                    groupId = nil;
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPGETGROUPMEMBERS object:nil];
                
            });

        }
        
         NSXMLElement *discusMembers = [iq elementForName:@"talkOverGroupUserList"];
        if (discusMembers) {
            if([[discusMembers xmlns] isEqualToString:@"com:im:wanzhao:GroupUserList"])
            {
                id mbers = [NSJSONSerialization JSONObjectWithData:[[discusMembers stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
                
                CGroupMemberMgr *mgr = [[CGroupMemberMgr alloc] init];
                if ([mbers isKindOfClass:[NSArray class]]) {
                    NSString *groupId = nil;
                    NSMutableArray *arrayM = [NSMutableArray array];
                    for (NSDictionary *dict in mbers) {
                        CGroupMemberModel *contact = [[CGroupMemberModel alloc] init];
                        contact.UserId = [dict objectForKey:@"id"];
                        contact.GroupID = [dict objectForKey:@"groupId"];
                        groupId = contact.GroupID;
                        contact.Available = [dict boolForKey:@"available"];
                        contact.UserCode = [dict stringForKey:@"userCode"];
                        contact.LastTime = [NSString stringWithFormat:@"%@",[dict objectForKey:@"lastTime"]];
                        [arrayM addObject:contact];
                        //                [mgr insetGroupMember:contact];
                    }
                    [mgr delAllGroupMembeWithGroupId:groupId];
                    [mgr batchInsertGroupMember:arrayM];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPGETDISCUSSIONMEMLIST object:nil];
                
            });
 
        }

        
    });
    return YES;
}




-(BOOL)handleGroupInfo:(NSXMLElement *)groupInfo
{
    if([[groupInfo xmlns] isEqualToString:@"com:im:wanzhao:groupProperty"])
    {
//        NSArray *children = [groupInfo children];
//        for(NSXMLElement *index in children)
//        {
////            NSLog(@"name:%@ value:%@", [index name], [index stringValue] );／
//        }
    }
    return YES;
}

- (void)handleKefuList:(XMPPIQ *)iq
{
    //客服联系人如果是本公司的则isdel＝1，yuLiuZiduan3 ＝ iskefu，若为其他公司的责isdel ＝ 0，yuLiuZiduan3 ＝ iskefu；
    dispatch_async(self.xmppMgrQueen, ^{
        CContactMgr *contactMgr = [[CContactMgr alloc] init];
        NSXMLElement *deptNode = [iq elementForName:@"result"];
        if(deptNode != nil)
        {
            NSXMLElement *companykf = [deptNode elementForName:@"companykf"];
            NSString *str = [companykf stringValue];
            NSError *error = nil;
            id jsonObject = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
            
            if([jsonObject isKindOfClass:[NSArray class]])
            {
                [jsonObject enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
                    
                    CContactModel *contactModel = [contactMgr loadContactWithUserId:[index objectForKey:@"id"]];
                    if (contactModel) {
                       contactModel.yuLiuZiduan3 = @"isKefu";
                        [contactMgr updateContact:contactModel];
                    } else {
                        contactModel = [[CContactModel alloc] init];
                        contactModel.UserID = [index objectForKey:@"id"];
                        contactModel.UserCode = [index objectForKey:@"userCode"];
                        contactModel.UserName = [index objectForKey:@"realName"];
                        contactModel.yuLiuZiduan3 = @"isKefu";
                        contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                        contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:contactModel.UserName] lowercaseString];
                        contactModel.IsAvailable = @"离线";
                        [contactMgr insetContact:contactModel];
                    }
                    contactModel = nil;
                }];
                
                [USER_DEFAULT setBool:YES forKey:isKeFuCompleted];
                [USER_DEFAULT synchronize];

            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDGETKEFULIST object:nil];
        });
    });

}

-(BOOL)handleGroupList:(NSXMLElement *)groupList
{
    dispatch_async(self.xmppMgrQueen, ^{
    CGroupMgr *groupMgr = [[CGroupMgr alloc] init];
    CMessageMgr *mesMgr = [[CMessageMgr alloc] init];
    NSArray *groppIdArray = [mesMgr loadAllMessageGroupId];
    CMessageDraftMgr *draftMgr = [[CMessageDraftMgr alloc] init];
        NSArray *draftArray = [draftMgr loadAllmessageDraftGroupId];
    if([[groupList xmlns] isEqualToString:@"com:im:wanzhao:groupListForUser"])
    {
        id array = [NSJSONSerialization JSONObjectWithData:[[groupList stringValue] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:5];
        for (NSDictionary *index in array) {
            NSString *groupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(groupId)) {
                CGroupModel  *groupModel = [[CGroupModel alloc] init];
                groupModel.GroupId = groupId;
                groupModel.GroupName = [index stringForKey:@"name"];
                groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                groupModel.OwnerId = [index stringForKey:@"ownerId"];
                groupModel.UserNum = [index integerForKey:@"userCount"];
                groupModel.OwnerName = [index stringForKey:@"owner"];
                groupModel.GroupNotice = [index stringForKey:@"notice"];
                groupModel.GroupCreateDate = [index stringForKey:@"createDate"];
                groupModel.groupType = [index integerForKey:@"type"];
                groupModel.isShow = [index boolForKey:@"isHidden"];
                groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"name"]] lowercaseString];
                groupModel.IsDel = [index boolForKey:@"isDel"];
                [arrayM addObject:groupModel];
                groupModel = nil;
            }
        }
        
        NSArray *oldArray = [groupMgr loadAllGroupAndDiscussion];
        
        __block BOOL hasOld = NO;
        [oldArray enumerateObjectsUsingBlock:^(CGroupModel *old, NSUInteger idx, BOOL *stop) {
            hasOld = NO;
            for (CGroupModel *obj in arrayM) {
                if ([old.GroupId isEqualToString:obj.GroupId]) {
                    hasOld = YES;
                }
            }
            if (hasOld == NO) {
                [groupMgr delGroup:old];
            }
        
        }];
        [arrayM enumerateObjectsUsingBlock:^(CGroupModel *obj, NSUInteger idx, BOOL *stop) {
            [groupMgr insertGroup:obj];
        }];

        [USER_DEFAULT setBool:YES forKey:isGroupCompleted];
        [USER_DEFAULT synchronize];

        //删除群信息
        [groppIdArray enumerateObjectsUsingBlock:^(NSString *groupId, NSUInteger idx, BOOL *stop) {
            BOOL isexit = NO;
            for (CGroupModel *gro in arrayM) {
                if ([groupId isEqualToString:gro.GroupId]) {
                    isexit = YES;
                    break;
                }
            }
            if (!isexit) {
                [mesMgr delGroupMessageWithGroupId:groupId];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                });

            }
        }];
        //删除草稿信息
        [draftArray enumerateObjectsUsingBlock:^(NSString *groupId, NSUInteger idx, BOOL *stop) {
            BOOL isexit = NO;
            for (CGroupModel *gro in arrayM) {
                if ([groupId isEqualToString:gro.GroupId]) {
                    isexit = YES;
                    break;
                }
            }
            if (!isexit) {
                [draftMgr delMessageDraftWithGroupId:groupId];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                });
                
            }
        }];

    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETGROUPLIST object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
    });
    });
   return YES;
}

-(BOOL)handlePresence:(XMPPPresence *)presence sender:(XMPPStream *)sender
{
   
//     NSLog(@"5");
    dispatch_async(self.xmppMgrQueen, ^{

        NSString *presenceType = [presence type];
        NSString *presenceFromUser = [[[presence from] user] lowercaseString];
        NSString *presenceFromSource = [[[presence from] resource] lowercaseString];
        
        CPresenceMgr *mgr = [[CPresenceMgr alloc] init];
        CPresenceModel *cPresence = [mgr getPresenceWithUserCode:presenceFromUser];
        if (cPresence) {
            
            if ([presenceType isEqualToString:@"available"] ) {
                
                if ([presenceFromSource isEqualToString:@"pc"]) {
                    cPresence.pcAvailable = @"在线";
                } else if ([presenceFromSource isEqualToString:@"app"]) {
                    cPresence.IsAvailable = @"在线";
                } else {
                    cPresence.IsAvailable = @"在线";
                }
                
            } else if ([presenceType isEqualToString:@"unavailable"]) {
                
                if ([presenceFromSource isEqualToString:@"pc"]) {
                    cPresence.pcAvailable = @"离线";
                } else if ([presenceFromSource isEqualToString:@"app"]) {
                    cPresence.IsAvailable = @"离线";
                } else {
                    cPresence.IsAvailable = @"离线";
                }
            }
            
            [mgr updatePressenceWithPresence:cPresence];
            } else {
            cPresence = [[CPresenceModel alloc] init];
            cPresence.UserCode = presenceFromUser;
            if ([presenceType isEqualToString:@"available"] ) {
                
                if ([presenceFromSource isEqualToString:@"pc"]) {
                    cPresence.pcAvailable = @"在线";
                } else if ([presenceFromSource isEqualToString:@"app"]) {
                    cPresence.IsAvailable = @"在线";
                } else {
                    cPresence.IsAvailable = @"在线";
                }
                
            } else if ([presenceType isEqualToString:@"unavailable"]) {
                
                if ([presenceFromSource isEqualToString:@"pc"]) {
                    cPresence.pcAvailable = @"离线";
                } else if ([presenceFromSource isEqualToString:@"app"]) {
                    cPresence.IsAvailable = @"离线";
                } else {
                    cPresence.IsAvailable = @"离线";
                }
            }
                [mgr insetPresence:cPresence];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDRECEIVEPRESENCE object:nil];
        });

        
    });
    
    return YES;
//    NSLog(@"%@",[NSThread currentThread]);
}



-(BOOL)handleContactUser:(XMPPIQ *)iq
{
    NSXMLElement *query = nil;
    if([iq elementForName:@"recentcontactuser"])
    {
        query = [iq elementForName:@"recentcontactuser"];
    }
    else if([iq elementForName:@"recentcontactgroup"])
    {
        query = [iq elementForName:@"recentcontactgroup"];
    }
    else if([iq elementForName:@"recentusergroup"])
    {
        query = [iq elementForName:@"recentusergroup"];
    }
    
    if (query == nil)
    {
        return NO;
    }
    
    NSString *type = [[iq attributeStringValueForName:@"type"] lowercaseString];
    if ([type isEqualToString:@"get"])
    {
//        NSString *node = [query attributeStringValueForName:@"node"];
        
        //        if (node == nil || [node hasPrefix:DISCO_NODE])
        //        {
        //            [self handleDiscoRequest:iq];
        //        }
        //        else
        //        {
        //            return NO;
        //        }
    }
    else if ([type isEqualToString:@"result"])
    {
        [self handleDiscoResponse:query fromJID:[iq from]];
    }
    else if ([type isEqualToString:@"error"])
    {
        //        [self handleDiscoErrorResponse:query fromJID:[iq from]];
    }
    else
    {
        return NO;
    }
    
    return YES;

}


- (void)handleDiscoResponse:(NSXMLElement *)querySubElement fromJID:(XMPPJID *)jid
{

//    NSLog(@"querySubElement:%@  jid:%@", querySubElement, jid);
    
//    NSXMLElement *superElement = －querySubElement elementForName:@"recentcontactuser"];
    if([[querySubElement name] isEqualToString:@"recentcontactuser"])
    {
        NSArray *children = [querySubElement children];
        for(NSXMLElement *index in children)
        {
            if([[index name] isEqualToString:@"contactuser"])
            {
//                NSLog(@" usercode:%@ username:%@ tousercode:%@ tousername:%@ lasttime:%@", [index attributeForName:@"usercode"], [[index attributeForName:@"username"] stringValue], [index attributeForName:@"tousercode"], [[index attributeForName:@"tousername"] stringValue], [index attributeForName:@"lasttime"]);
            }
        }
    }
    else if([[querySubElement name] isEqualToString:@"recentcontactgroup"])//recentcontactgroup
    {
        NSArray *children = [querySubElement children];
        for(NSXMLElement *index in children)
        {
            if([[index name] isEqualToString:@"contactgroup"])
            {
//                NSLog(@" usercode:%@ username:%@  groupname:%@ lasttime:%@", [index attributeForName:@"usercode"], [[index attributeForName:@"username"] stringValue], [[index attributeForName:@"groupname"] stringValue], [index attributeForName:@"lasttime"]);
            }
        }
    }
    else if([[querySubElement name] isEqualToString:@"recentusergroup"])//recentcontactgroup
    {
        NSArray *children = [querySubElement children];
        for(NSXMLElement *index in children)
        {
            if([[index name] isEqualToString:@"usergroup"])
            {
            
            }
        }
    }
    

}




- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    
    dispatch_async(self.xmppMgrQueen, ^{
        BOOL other = [USER_DEFAULT boolForKey:isOtherContactCompleted];
        BOOL group = [USER_DEFAULT boolForKey:isGroupCompleted];
        BOOL kefu = [USER_DEFAULT boolForKey:isKeFuCompleted];
        while (!other|| !group || !kefu) {
            sleep(2);
        }
    
    CContactMgr *conMgr = [[CContactMgr alloc] init];
    CGroupMgr *gropuMgr = [[CGroupMgr alloc] init];
    CMessageMgr *mesMgr = [[CMessageMgr alloc] init];
    CUserSettingModel *userSetting = [[[CUserSettingMgr alloc] init] getUserSetting];
    CContactModel *curModel = [conMgr loadCurContact];
      
    if ([message.from.user isEqualToString:curModel.UserCode] && [message.from.resource isEqualToString:@"app"]) {
        return;
    }
        
    NSDateComponents *cmp = [UIUtil getCurdateComponents];
    
     BOOL isDisturb = NO;
    
    if (userSetting.Disturb) {
        if ((cmp.hour >= 0 && cmp.hour < 8) || cmp.hour == 23) {
            isDisturb = YES;
        } else {
            isDisturb = NO;
        }
    }
   // A simple example of inbound message handling.
    
    if ([message isChatMessageWithBody])
    {
        NSString *body = [[message elementForName:@"body"] stringValue];
        NSString *subject = [[message elementForName:@"subject"] stringValue];
        body = [body stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
        body = [body stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        body = [body stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        id jsBody = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        if ([jsBody isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = (NSDictionary *)jsBody;
            NSDictionary *subDic = dict[@"messageCommon"];
            //        NSLog(@"%@=======subDic",subDic);
            
            NSString *Messagetype = [subDic stringForKey:@"type"];
            if ([Messagetype isEqualToString:@"text"] || [Messagetype isEqualToString:@"file"] || [Messagetype isEqualToString:@"image"] || [Messagetype isEqualToString:@"voice"]||[Messagetype isEqualToString:@"video"] || [Messagetype isEqualToString:@"redpacket"])  {
                if ([[subDic objectForKey:@"status"] isEqualToString:@"cancel"]) {
                    return;
                }
                CMessageModel *model = [[CMessageModel alloc] init];
                
                model.MessageContent = [[subDic stringForKey:@"body"] stringByReplacingOccurrencesOfString:@"ΨEnterΨ" withString:@"\n"];
                model.FriendJid = message.from.bare;
                model.MineJid = message.to.bare;
                model.FileName = [subDic stringForKey:@"fileName"];
                model.Stream = [subDic stringForKey:@"stream"];
                model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
                model.yuLiuZiduan1 = [subDic stringForKey:@"companyId"];
                NSString *nodeId =[[subDic stringForKey:@"nodeId"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
                
                model.MessageId = [NSString stringWithFormat:@"%@-%@",[subDic objectForKey:@"messageId"],nodeId];

                //        model.GroupId = [subDic stringForKey:@"groupId"];
                model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
                model.FriendUserId = [subDic stringForKey:@"fromId"];
                model.MineUserId = [subDic stringForKey:@"toId"];
                model.SoundPlayStatus = MessageSoundNotPlay;
                model.MessageSendedStatus = kMessageOK;
                //加载联系人信息
                
                
                model.FriendUserName = [subDic stringForKey:@"fromName"];
                model.MineUserName = [subDic stringForKey:@"toName"];
                
               
                model.IsShowInmessageList = YES;
                if ([subDic[@"status"] integerValue] == 0) {
                    model.ReadStatus = NO;
                } else {
                    model.ReadStatus = YES;
                }
                model.MessageType = [subDic stringForKey:@"type"];
                
                
                if ([model.MessageType isEqualToString:@"image"]||[Messagetype isEqualToString:@"video"]) {
                    NSString *stremString = subDic[@"stream"];
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[stremString dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil];
                    model.Stream = [dict objectForKey:model.FileName];
                   
                }
                
                if ([model.MessageType isEqualToString:@"file"]) {
                    
                    if ([subDic[@"status"] isEqualToString:@"yes/no"]) {
                        model.ReadStatus = NO;
                    } else {
                        model.ReadStatus = YES;
                    }
                    
                } else {
                    
                }
                
                if ([model.FriendUserId isEqualToString:curModel.UserID]) {
                    model.MineUserId = [subDic stringForKey:@"fromId"];
                    model.FriendUserId = [subDic stringForKey:@"toId"];
                    
                    model.FriendUserName = [subDic stringForKey:@"toName"];
                    model.MineUserName = [subDic stringForKey:@"fromName"];
                    
                    model.isMineSend = YES;
                    model.ReadStatus = YES;

                    if ([model.FriendUserId isEqualToString:model.MineUserId]) {
                        model.FriendUserName = @"我的电脑";
                        model.MineUserName = @"我的手机";
                        model.isMineSend = NO;
                        model.ReadStatus = NO;
                    }
                } else {
                    model.isMineSend = NO;
                }

                if (model.TimeStamp.length <= 0) {
                    model.TimeStamp = [UIUtil getCurrentTimeStamp];
                }
                CContactModel *contact = [conMgr loadNotDelContactWithUserId:model.FriendUserId];
                if ([[subDic stringForKey:@"fromId"] isEqualToString:curModel.UserID]) {
                    if (contact) {
                        //bug 9337 fixed by lixu
                        curModel.compCode = [subDic stringForKey:@"companyId"];
                        [conMgr insetContact:curModel];
                        if (contact.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                            model.ReadStatus = YES;
                            
                        }
                    } else {
                        if (![[message.from.user componentsSeparatedByString:@"_"].lastObject isEqualToString:[message.to.user componentsSeparatedByString:@"_"].lastObject]) {
                            contact = [[CContactModel alloc] init];
                            contact.PinYin = [[[NSString pinyinWithHanzi:model.FriendUserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                            contact.UserCode = message.from.user;
                            contact.UserID = model.FriendUserId;
                            contact.UserName = model.FriendUserName;
                            contact.yuLiuZiduan3 = @"isWaibu";
                            [conMgr insetContact:contact];
                        }
                    }

                }
               else
               {
                if (contact) {
                    //bug 9337 fixed by lixu
                     contact.compCode = [subDic stringForKey:@"companyId"];
                    [conMgr insetContact:contact];
                    if (contact.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                    model.ReadStatus = YES;
                      
                    }
                } else {
                    if (![[message.from.user componentsSeparatedByString:@"_"].lastObject isEqualToString:[message.to.user componentsSeparatedByString:@"_"].lastObject]) {
                        contact = [[CContactModel alloc] init];
                        contact.PinYin = [[[NSString pinyinWithHanzi:model.FriendUserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                        contact.UserCode = message.from.user;
                        contact.UserID = model.FriendUserId;
                        contact.UserName = model.FriendUserName;
                        contact.compCode = [subDic stringForKey:@"companyId"];
                        contact.yuLiuZiduan3 = @"isWaibu";
                        [conMgr insetContact:contact];
                    }
                }
               }
                if (contact) {
                    
                    
                    BOOL ret = [mesMgr insertMessage:model];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if (ret) {
                            [[CXmppRequestMgr shareInstance] sendHuiZhiXiaoxiWithMessageId:[[message attributeForName:@"id"] stringValue]];
                        }

                        BOOL ishasVoice = NO;
                        if (model.ReadStatus == NO) {
                            if (!isDisturb) {
                                if (contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND && userSetting.Shake) {
                                    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                        [UIUtil playSystemAlert];
                                    }
                                    
                                        
                                }
                                if (contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND && userSetting.Voice) {
                                    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                        [UIUtil playSystemSoundForMessage];

                                    }
                                    ishasVoice = YES;
                                }

                            }
                            
                        }
                        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && ![[subDic stringForKey:@"fromId"] isEqualToString:curModel.UserID] && contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND)
                        {
                            self.noticeNum ++;
                            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                            localNotification.alertAction = @"查看";
                            if (ishasVoice) {
                                localNotification.soundName = UILocalNotificationDefaultSoundName;
                            }
                            if ([model.MessageType isEqualToString:@"file"]) {
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一个文件"];
                            } else if ([model.MessageType isEqualToString:@"image"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一张图片"];
                            } else if ([model.MessageType isEqualToString:@"voice"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一段语音"];
                            } else if ([model.MessageType isEqualToString:@"text"]) {
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,model.MessageContent];
                            } else if([model.MessageType isEqualToString:@"video"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一个小视频"];
                            } else if([model.MessageType isEqualToString:@"redpacket"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一个红包"];
                            }

                            localNotification.applicationIconBadgeNumber = self.noticeNum;//标记数
                            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];//发送通知
                        }
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEMESSAGE object:nil];

                        
                    });

                }
            }

        }
        else if ([subject isEqualToString:@"offline"] && [jsBody isKindOfClass:[NSArray class]]){
            NSMutableArray *offlinArrayM = [NSMutableArray array];
            
            __block CContactModel *contact = nil;
            __block CMessageModel *modelM = nil;
            [jsBody enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
                
                NSDictionary *subDic = dict[@"messageCommon"];
                NSString *Messagetype = [subDic stringForKey:@"type"];
                if ([Messagetype isEqualToString:@"text"] || [Messagetype isEqualToString:@"file"] || [Messagetype isEqualToString:@"image"] || [Messagetype isEqualToString:@"voice"]||[Messagetype isEqualToString:@"video"] || [Messagetype isEqualToString:@"redpacket"]) {
                    if ([[subDic objectForKey:@"status"] isEqualToString:@"cancel"]) {
                        return;
                    }
                    CMessageModel *model = [[CMessageModel alloc] init];
                    
                    model.MessageContent = [[subDic stringForKey:@"body"] stringByReplacingOccurrencesOfString:@"ΨEnterΨ" withString:@"\n"];
                    model.FriendJid = message.from.bare;
                    model.MineJid = message.to.bare;
                    model.FileName = [subDic stringForKey:@"fileName"];
                    model.Stream = [subDic stringForKey:@"stream"];
                    model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
                    NSString *nodeId =[[subDic stringForKey:@"nodeId"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    
                    model.MessageId = [NSString stringWithFormat:@"%@-%@",[subDic objectForKey:@"messageId"],nodeId];

                    //        model.GroupId = [subDic stringForKey:@"groupId"];
                    model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
                    model.FriendUserId = [subDic stringForKey:@"fromId"];
                    model.MineUserId = [subDic stringForKey:@"toId"];
                    model.SoundPlayStatus = MessageSoundNotPlay;
                    model.MessageSendedStatus = kMessageOK;
                    //加载联系人信息
                
                    
                    model.FriendUserName = [subDic stringForKey:@"fromName"];
                    model.MineUserName = [subDic stringForKey:@"toName"];
                    
                    model.IsShowInmessageList = YES;
                    if ([subDic[@"status"] integerValue] == 0) {
                        model.ReadStatus = NO;
                    } else {
                        model.ReadStatus = YES;
                    }
                    model.MessageType = [subDic stringForKey:@"type"];
                    if ([model.MessageType isEqualToString:@"image"]||[model.MessageType isEqualToString:@"video"]) {
                        NSString *stremString = subDic[@"stream"];
                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[stremString dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil];
                        model.Stream = [dict objectForKey:model.FileName];
                    }
                    
                    if ([model.MessageType isEqualToString:@"file"]) {
                        if ([subDic[@"status"] isEqualToString:@"yes/no"]) {
                            model.ReadStatus = NO;
                        } else {
                            model.ReadStatus = YES;
                        }
                        
                    }
                    
                    if ([model.FriendUserId isEqualToString:curModel.UserID]) {
                        model.MineUserId = [subDic stringForKey:@"fromId"];
                        model.FriendUserId = [subDic stringForKey:@"toId"];
                        
                        model.FriendUserName = [subDic stringForKey:@"toName"];
                        model.MineUserName = [subDic stringForKey:@"fromName"];
                        
                        model.isMineSend = YES;
                        model.ReadStatus = YES;
                        
                        if ([model.FriendUserId isEqualToString:model.MineUserId]) {
                            model.FriendUserName = @"我的电脑";
                            model.MineUserName = @"我的手机";
                            model.isMineSend = NO;
                            model.ReadStatus = NO;
                        }

                    } else {
                        model.isMineSend = NO;
                    }
                    
                    contact = [conMgr loadContactWithUserId:model.FriendUserId];
                    
                    if (model.TimeStamp.length <= 0) {
                        model.TimeStamp = [UIUtil getCurrentTimeStamp];
                    }
                    
                    if (contact.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                        model.ReadStatus = YES;
                    }

                    [offlinArrayM addObject:model];
                    model.yuLiuZiduan1 = [subDic stringForKey:@"companyId"];
                    modelM = model;
                    model = nil;
                }
                
            }];
            if (contact) {
                contact.compCode = modelM.yuLiuZiduan1;
                [conMgr insetContact:contact];
            } else {
                if (![[message.from.user componentsSeparatedByString:@"_"].lastObject isEqualToString:[message.to.user componentsSeparatedByString:@"_"].lastObject]) {
                    contact = [[CContactModel alloc] init];
                    contact.UserCode = message.from.user;
                    contact.UserID = modelM.FriendUserId;
                    contact.UserName = modelM.FriendUserName;
                    contact.compCode = modelM.yuLiuZiduan1;
                    
                    contact.yuLiuZiduan3 = @"isWaibu";
                    [conMgr insetContact:contact];
                }
            }

            
            if (contact) {
               BOOL ret = [mesMgr batchInsertMessages:[offlinArrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"TimeStamp" ascending:YES]]]];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (ret) {
                        [[CXmppRequestMgr shareInstance] sendHuiZhiXiaoxiWithMessageId:[[message attributeForName:@"id"] stringValue]];
                        
                    }

                    NSInteger unReadCount = [mesMgr loadUnReadCountWithMineUserId:curModel.UserID FriendUserId:contact.UserID];
                    if (unReadCount > 0) {
                        if (!isDisturb) {
                            if (contact.messageSettingType == 0 && userSetting.Shake) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemAlert];
                                }

                            }
                            if (contact.messageSettingType == 0 && userSetting.Voice) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemSoundForMessage];
                                }

                               
                            }
                            
                        }
                    }
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEMESSAGE object:nil];
                });
            }
        }
    }
    else if ([message isGroupMessageWithBody]){
        NSString *body = [[message elementForName:@"body"] stringValue];
        NSString *subject = [[message elementForName:@"subject"] stringValue];
        body = [body stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
        body = [body stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        body = [body stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        NSError *error;
       id jsBody = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
        
        if ([jsBody isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = (NSDictionary *)jsBody;
            NSDictionary *subDic = dict[@"messageCommon"];
            NSString *Messagetype = [subDic stringForKey:@"type"];
            if ([Messagetype isEqualToString:@"text"] || [Messagetype isEqualToString:@"file"] || [Messagetype isEqualToString:@"image"] || [Messagetype isEqualToString:@"voice"]||[Messagetype isEqualToString:@"video"] || [Messagetype isEqualToString:@"redpacket"]) {
                
                if ([[subDic objectForKey:@"status"] isEqualToString:@"cancel"]) {
                    return;
                }
                
                CMessageModel *model = [[CMessageModel alloc] init];
                
                model.MessageContent = [[subDic stringForKey:@"body"] stringByReplacingOccurrencesOfString:@"ΨEnterΨ" withString:@"\n"];
                model.FriendJid = message.from.bare;
                model.MineJid = message.to.bare;
                model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
                model.FileName = [subDic stringForKey:@"fileName"];
                model.Stream = [subDic stringForKey:@"stream"];
                
                NSString *nodeId =[[subDic stringForKey:@"nodeId"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
                
                model.MessageId = [NSString stringWithFormat:@"%@-%@",[subDic objectForKey:@"messageId"],nodeId];
                
                model.GroupId = [subDic stringForKey:@"groupId"];
                
                model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
                model.FriendUserId = [subDic stringForKey:@"toId"];
                model.MineUserId = [subDic stringForKey:@"fromId"];
                model.SoundPlayStatus = MessageSoundNotPlay;
                model.MessageSendedStatus = kMessageOK;
                
                //加载群信息
                CGroupModel *group = [gropuMgr loadGroup:model.GroupId];
                
                model.MineUserName = [subDic stringForKey:@"fromName"];
                model.FriendUserName = [subDic stringForKey:@"toName"];
               
                model.IsShowInmessageList = YES;
                if ([subDic[@"status"] integerValue] == 0) {
                    model.ReadStatus = NO;
                } else {
                    model.ReadStatus = YES;
                }
                model.MessageType = [subDic stringForKey:@"type"];
                if ([model.MessageType isEqualToString:@"image"]||[model.MessageType isEqualToString:@"video"]) {
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[subDic[@"stream"] dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil];
                    model.Stream = [dict objectForKey:model.FileName];
                    
                }
                if ([model.MessageType isEqualToString:@"file"]) {
                    model.FileCacheName = @"upLoadGroupFile";
                    if (group) {
                        group.yuLiuZiduan2 = 1;
                        [gropuMgr  updateGroup:group];
                    }

                    [USER_DEFAULT setBool:YES forKey:ISSHOWCHATREDDOPT];
                    [USER_DEFAULT synchronize];
                    if ([subDic[@"status"] isEqualToString:@"yes/no"]) {
                        model.ReadStatus = NO;
                    } else {
                        model.ReadStatus = YES;
                    }
                    
                } else {
                    model.FileCacheName = @"noUpLoadGroupFile";
                    if (group) {
                        group.yuLiuZiduan2 = 0;
                        [gropuMgr updateGroup:group];
                    }
                }
                
                if (model.TimeStamp.length <= 0) {
                    model.TimeStamp = [UIUtil getCurrentTimeStamp];
                }
                
                if ([model.MineUserId isEqualToString:curModel.UserID]) {
                    model.isMineSend = YES;
                    model.ReadStatus = YES;
                } else {
                    model.isMineSend = NO;
                }
                
                
                
                if (group) {
                    
                    if (group.groupType == 1) {
                        model.yuLiuZiduan2 = 1;
                        if (!group.isShow) {
                            group.isShow = YES;
                            [gropuMgr updateGroup:group];
                        }
                    }

                    if (group.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                        model.ReadStatus = YES;
                    }
                    BOOL ret = [mesMgr insertMessage:model];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (ret) {
                            [[CXmppRequestMgr shareInstance] sendHuiZhiXiaoxiWithMessageId:[[message attributeForName:@"id"] stringValue]];
                            
                        }

                        BOOL isHasVoice = NO;
                        if (model.ReadStatus == NO) {
                            if (!isDisturb) {
                                
                                if (userSetting.Shake && group.messageSettingType == 0) {
                                    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                        [UIUtil playSystemAlert];
                                    }

                                    
                                }
                                if (userSetting.Voice  && group.messageSettingType == 0) {
                                    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                        [UIUtil playSystemSoundForMessage];
                                    }

                                    isHasVoice = YES;
                                }
                            }
                        }
                        
                        if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && ![model.MineUserId isEqualToString:curModel.UserID] && group.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND)
                        {
                            self.noticeNum ++;
                            
                            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                            localNotification.alertAction  = @"查看";
                            if (isHasVoice) {
                               localNotification.soundName = UILocalNotificationDefaultSoundName;
                            }
                            if ([model.MessageType isEqualToString:@"file"]) {
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,@"发来一个文件"];
                            } else if ([model.MessageType isEqualToString:@"image"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,@"发来一张图片"];
                            } else if ([model.MessageType isEqualToString:@"voice"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,@"发来一段语音"];
                            } else if ([model.MessageType isEqualToString:@"text"]) {
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,model.MessageContent];
                            }else if ([model.MessageType isEqualToString:@"video"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,@"发来一个小视频"];
                            }else if ([model.MessageType isEqualToString:@"redpacket"]){
                                localNotification.alertBody = [NSString stringWithFormat:@"%@(%@):%@",model.MineUserName,model.FriendUserName,@"发来一个红包"];
                            }

                            //            localNotification.soundName = @"crunch.wav";//通知声音
                            localNotification.applicationIconBadgeNumber = self.noticeNum;//标记数
                            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];//发送通知
                            
                        }
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEMESSAGE object:nil];
                        
                    });

                }
                
            }
            if ([Messagetype isEqualToString:@"System"]) {
                
            }

        }
        else if ([subject isEqualToString:@"offline"] && [jsBody isKindOfClass:[NSArray class]]){
            NSMutableArray *offlinArrayM = [NSMutableArray array];
            __block CGroupModel *group;
           [jsBody enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
               
           
                NSDictionary *subDic = dict[@"messageCommon"];
                NSString *Messagetype = [subDic stringForKey:@"type"];
                if ([Messagetype isEqualToString:@"text"] || [Messagetype isEqualToString:@"file"] || [Messagetype isEqualToString:@"image"] || [Messagetype isEqualToString:@"voice"]||[Messagetype isEqualToString:@"video"]||[Messagetype isEqualToString:@"redpacket"]) {
                    
                    if ([[subDic objectForKey:@"status"] isEqualToString:@"cancel"]) {
                        return;
                    }
                    
                    CMessageModel *model = [[CMessageModel alloc] init];
                    
                    model.MessageContent = [[subDic stringForKey:@"body"] stringByReplacingOccurrencesOfString:@"ΨEnterΨ" withString:@"\n"];
                    model.FriendJid = message.from.bare;
                    model.MineJid = message.to.bare;
                    model.FileSize = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"length"]];
                    model.FileName = [subDic stringForKey:@"fileName"];
                    model.Stream = [subDic stringForKey:@"stream"];
                    NSString *nodeId =[[subDic stringForKey:@"nodeId"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
                    model.MessageId = [NSString stringWithFormat:@"%@-%@",[subDic objectForKey:@"messageId"],nodeId];
                    model.GroupId = [subDic stringForKey:@"groupId"];
                    
                    model.TimeStamp = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"sendTime"]];
                    model.FriendUserId = [subDic stringForKey:@"toId"];
                    model.MineUserId = [subDic stringForKey:@"fromId"];
                    model.SoundPlayStatus = MessageSoundNotPlay;
                    model.MessageSendedStatus = kMessageOK;
                    
                    //加载群信息
                    group = [gropuMgr loadGroup:model.GroupId];
                    
                    model.MineUserName = [subDic stringForKey:@"fromName"];
                    model.FriendUserName = [subDic stringForKey:@"toName"];
                    
                    model.IsShowInmessageList = YES;
                    if ([subDic[@"status"] integerValue] == 0) {
                        model.ReadStatus = NO;
                    } else {
                        model.ReadStatus = YES;
                    }
                    model.MessageType = [subDic stringForKey:@"type"];
                    if ([model.MessageType isEqualToString:@"image"]||[model.MessageType isEqualToString:@"video"]) {
                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[subDic[@"stream"] dataUsingEncoding:NSUTF8StringEncoding]  options:0 error:nil];
                        model.Stream = [dict objectForKey:model.FileName];
                        
                    }
                    if ([model.MessageType isEqualToString:@"file"]) {
                        model.FileCacheName = @"upLoadGroupFile";
                        //标记群聊天界面的小红点
                        if (group) {
                            
                            group.yuLiuZiduan2 = 1;
                            [gropuMgr updateGroup:group];
                        }
                        if ([subDic[@"status"] isEqualToString:@"yes/no"]) {
                            model.ReadStatus = NO;
                        } else {
                            model.ReadStatus = YES;
                        }
                        
                    } else {
                        if (group) {
                            
                            group.yuLiuZiduan2 = 0;
                            [gropuMgr updateGroup:group];
                        }

                        model.FileCacheName = @"noUpLoadGroupFile";
                    }
                    
                    if ([model.MineUserId isEqualToString:curModel.UserID]) {
                        
                        model.isMineSend = YES;
                        model.ReadStatus = YES;
                    } else {
                        model.isMineSend = NO;
                    }

                    if (model.TimeStamp.length <= 0) {
                        model.TimeStamp = [UIUtil getCurrentTimeStamp];
                    }
                    
                    if (group.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                        model.ReadStatus = YES;
                    }
                    if (group.groupType == 1) {
                        model.yuLiuZiduan2 = 1;
                    }
                    [offlinArrayM addObject:model];
                    model = nil;
                    }
           }];
            
            if (group) {
                
                if (group.groupType == 1) {
                    
                    if (!group.isShow) {
                        group.isShow = YES;
                        [gropuMgr updateGroup:group];
                    }
                }
                BOOL ret = [mesMgr batchInsertMessages:[offlinArrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"TimeStamp" ascending:YES]]]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (ret) {
                        [[CXmppRequestMgr shareInstance] sendHuiZhiXiaoxiWithMessageId:[[message attributeForName:@"id"] stringValue]];
                        
                    }

                    NSInteger groupUnreadCount = [mesMgr loadGroupUnReadCountWithGroupdId:group.GroupId];
                    if (groupUnreadCount > 0) {
                        if (!isDisturb) {
                            if (userSetting.Shake && group.messageSettingType == 0) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemAlert];
                                }

                            }
                            if (userSetting.Voice  && group.messageSettingType == 0) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemSoundForMessage];                                }
                            }
                        }
                    }
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEMESSAGE object:nil];
                });
            }
        }
//        NSLog(@"%@=======subDic",subDic);
    }
    else {
        
        if ([message attributeForName:@"reply"]) {
            CMessageModel *mes = [mesMgr loadMessageWithMessageId:[[message attributeForName:@"id"] stringValue]];
            mes.MessageSendedStatus = kMessageOK;
            [mesMgr updateMessage:mes];
           
            [self.safeDict removeObjectForKey:[[message attributeForName:@"id"] stringValue]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDSENDMESSAGE object:mes.MessageId];
                
            });
            
            return;
        }

        
        NSString *body = [[message elementForName:@"body"] stringValue];
        
        if (body) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSDictionary *sudic = dict[@"messageCommon"];
            
            if(sudic == nil) return;
            NSString *type = [NSString stringWithFormat:@"%@",[sudic objectForKey:@"type"]];
            if (type == nil) return;
            //bug 8839 8841 fixed by lixu
            if ([type isEqualToString:@"returnCompanyKfUpdate"]) {
                
                 if([sudic objectForKey:@"body"] == nil) return;
                NSString *arrayStr = [sudic objectForKey:@"body"];
                NSError *error = nil;
                id jsonObject = [NSJSONSerialization JSONObjectWithData:[arrayStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
                CContactMgr *contactMgr = [[CContactMgr alloc] init];
                if([jsonObject isKindOfClass:[NSArray class]])
                {
                    
                    [contactMgr deleAllKeFuContact];
                    [jsonObject enumerateObjectsUsingBlock:^(NSDictionary *index, NSUInteger idx, BOOL *stop) {
                        
                        CContactModel *contactModel = [contactMgr loadContactWithUserId:[index objectForKey:@"id"]];
                        if (contactModel) {
                            contactModel.yuLiuZiduan3 = @"isKefu";
                            [contactMgr updateContact:contactModel];
                        } else {
                            
                            contactModel = [[CContactModel alloc] init];
                            contactModel.UserID = [index objectForKey:@"id"];
                            contactModel.UserCode = [index objectForKey:@"userCode"];
                            contactModel.UserName = [index objectForKey:@"realName"];
                            contactModel.yuLiuZiduan3 = @"isKefu";
                            contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                            contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:contactModel.UserName] lowercaseString];
                            contactModel.IsAvailable = @"在线";
                            [contactMgr insetContact:contactModel];
                        }
                        contactModel = nil;
                    }];
                    
                    [USER_DEFAULT setBool:YES forKey:isKeFuCompleted];
                    [USER_DEFAULT synchronize];
                    
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
                });
    
            }
        else if ([type isEqualToString:@"returnUserUpdate"]) {
            if([sudic objectForKey:@"body"] == nil) return;
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            NSDictionary *infoState = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[index objectForKey:@"infostate"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            
            CContactModel *contactModel = [conMgr loadContactWithUserId:[NSString stringWithFormat:@"%@",[index objectForKey:@"id"]]];
//            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
//            CDepartmentModel *oldDepmodel = [depMgr loadDepartment:contactModel.DEPTID];
            
//            [self delDepNumberWithDepId:contactModel.DEPTID depMgr:depMgr];
            
//            if (oldDepmodel) {
            
//                oldDepmodel.UserNum = oldDepmodel.UserNum - 1;
//                [depMgr updateDepartment:oldDepmodel];
//            }
            //bug 6303 fixed BY 荣则兵
            [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contactModel.UserID]];
            [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contactModel.UserID] fromDisk:YES];
            contactModel.UserCode = [index objectForKey:@"userCode"];
            contactModel.DEPTID = [index objectForKey:@"deptId"];
            contactModel.UserName = [index objectForKey:@"realName"];
            contactModel.EXtenSion = [index objectForKey:@"extension"];
            contactModel.Autograph = [index objectForKey:@"autograph"];
            contactModel.Position = [index objectForKey:@"position"];
            contactModel.RoleID = [index objectForKey:@"roleId"];
            contactModel.Telephone = [index objectForKey:@"telephone"];
            contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
            contactModel.Email = [index objectForKey:@"email"];
            contactModel.HeadPortrait = [index objectForKey:@"HeadPortrait"];
            contactModel.DEPNAME = [index objectForKey:@"dept"];
            contactModel.SEX = [index objectForKey:@"sex"];
            contactModel.address = [index objectForKey:@"address"];
            contactModel.birthDay = [index objectForKey:@"birthday"];
            contactModel.msgNoticeSet = [NSString stringWithFormat:@"%@",[infoState objectForKey:@"msgNoticeSet"]];
            contactModel.img = [NSString stringWithFormat:@"%@",[infoState objectForKey:@"img"]];
            contactModel.info = [NSString stringWithFormat:@"%@",[infoState objectForKey:@"info"]];
//            [self addDepNumberWithDepId:contactModel.DEPTID depMgr:depMgr];
            
//            CDepartmentModel *newDepModel = [depMgr loadDepartment:contactModel.DEPTID];
//            if (newDepModel) {
//                newDepModel.UserNum = newDepModel.UserNum + 1;
//                [depMgr updateDepartment:newDepModel];
//            }

            
            [conMgr updateContact:contactModel];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
            });
        } else if ([type isEqualToString:@"updateHeadImg"]){
            
            NSString *fileName = [sudic objectForKey:@"fileName"];
            if (fileName == nil) {
                return;
            }
            NSString *headId = [fileName stringByReplacingOccurrencesOfString:@".png" withString:@""];
            headId = [headId stringByReplacingOccurrencesOfString:@".jpg" withString:@""];
            [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:headId]];
            [[SDWebImageManager sharedManager].imageCache removeImageForKey:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:headId] fromDisk:YES];
            
        } else if ([type isEqualToString:@"returnMessageState"]) {
        
            NSDictionary *subBody = [NSJSONSerialization JSONObjectWithData:[[sudic objectForKey:@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSString *mesIds = [NSString stringWithFormat:@"%@",[subBody objectForKey:@"messageIds"]];
            if (M_ISSTRNULL(mesIds)) {
                return;
            }
//            NSArray *allUnreadMessage = [mesMgr loadAllUnReadMessgeID];
            NSArray *array = [mesIds componentsSeparatedByString:@","];
         
            for (NSString *mesId in array) {
//                for (CMessageModel *model in allUnreadMessage) {
//                    if ([model.MessageId hasPrefix:mesId]) {
                        [mesMgr updateMessageReadStatusWithMessageId:mesId];
//                    }
//                }
            }
           
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGESTATUES object:nil];
            });
            

        } else if ([type isEqualToString:@"returnSoundState"]){
        
            NSDictionary *subBody = [NSJSONSerialization JSONObjectWithData:[[sudic objectForKey:@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSString *mesIds = [NSString stringWithFormat:@"%@",[subBody objectForKey:@"messageIds"]];

            if (M_ISSTRNULL(mesIds)) {
                return;
            }
            NSArray *array = [mesIds componentsSeparatedByString:@","];
            for (NSString *mesId in array) {
                [mesMgr updateMessageSoundStatusWithMessageId:mesId];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"removeRedPoint" object:array.lastObject];
            });

        } else if ([type isEqualToString:@"returnUserAdd"]){
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

            
            CContactModel *contactModel = [conMgr loadContactWithUserId:[index objectForKey:@"id"]];
            if (contactModel==nil) {
                contactModel = [[CContactModel alloc] init];
                contactModel.DEPTID = [index objectForKey:@"deptId"];
                contactModel.UserID = [index objectForKey:@"id"];
                contactModel.UserCode = [index objectForKey:@"userCode"];
                contactModel.UserName = [index objectForKey:@"realName"];
                contactModel.EXtenSion = [index objectForKey:@"extension"];
                contactModel.Autograph = [index objectForKey:@"autograph"];
                contactModel.Position = [index objectForKey:@"position"];
                contactModel.RoleID = [index objectForKey:@"roleId"];
                contactModel.Telephone = [index objectForKey:@"telephone"];
                contactModel.MobileTelephone = [index objectForKey:@"mobilePhone"];
                contactModel.Email = [index objectForKey:@"email"];
                contactModel.isDel = [[index objectForKey:@"isDel"] boolValue];
                contactModel.HeadPortrait = [NSString stringWithFormat:@"%@",[index objectForKey:@"HeadPortrait"]];
                contactModel.DEPNAME = [NSString stringWithFormat:@"%@",[index objectForKey:@"dept"]];
                contactModel.SEX = [NSString stringWithFormat:@"%@",[index objectForKey:@"sex"]];
                contactModel.address = [NSString stringWithFormat:@"%@",[index objectForKey:@"address"]];
                contactModel.birthDay = [NSString stringWithFormat:@"%@",[index objectForKey:@"birthday"]];
                contactModel.PinYin = [[[NSString pinyinWithHanzi:contactModel.UserName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                contactModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"realName"]] lowercaseString];
                [conMgr insetContact:contactModel];
            }
            
            
            
//            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
//            [self addDepNumberWithDepId:contactModel.DEPTID depMgr:depMgr];
//            CDepartmentModel *dep = [depMgr loadDepartment:contactModel.DEPTID];
//            dep.UserNum = dep.UserNum + 1;
//            [depMgr updateDepartment:dep];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
            });
        } else if ([type isEqualToString:@"returnUserDel"]) {
            
            NSArray *index = [[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] componentsSeparatedByString:@","];
            
//            [cmgr delContactWithContactId:[NSString stringWithFormat:@"%@",index.firstObject]];
            [conMgr updateContactIsDelWithUserId:[NSString stringWithFormat:@"%@",index.firstObject] isDel:NO];
            if ([curModel.UserID isEqualToString:index.firstObject]) {
                UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                for (UIViewController *vc in rotNav.childViewControllers) {
                    if ([vc isKindOfClass:[LoginViewController class]]) {
                        LoginViewController *login = (LoginViewController *)vc;
                        [login setverifyStatus:NO];
                        login.errTimes = 0;
                        login.isUseverifyCode = NO;
                        [login setErrStatus:NO errorMsg:nil];
                    }
                }
                [rotNav popToRootViewControllerAnimated:NO];

            }
            else
            {
//                [[[CMessageMgr alloc]init] updateMessageWithIsShowInMessageList:NO FriendId:index.firstObject MineId:curModel.UserID];
                [[[CMessageMgr alloc]init] delMessageWithMineUserId:curModel.UserID FriendUserId:index.firstObject];
            }
            //            NSString *depId = index.lastObject;
//            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
//            [self delDepNumberWithDepId:depId depMgr:depMgr];
            
            
//            CDepartmentModel *dep = [depMgr loadDepartment:depId];
//            CDepartmentModel *fatherDep = [depMgr loadDepartment:dep.DeptFatherID];
//            dep.UserNum = dep.UserNum - 1;
//            [depMgr updateDepartment:dep];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDELETEUSER object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
            });
        } else if ([type isEqualToString:@"deptAdd"]) {
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            
            CDepartmentModel *departModel = [[CDepartmentModel alloc] init];
            departModel.DEPTID = [index objectForKey:@"id"];
            departModel.UserNum = [[index objectForKey:@"userNum"] intValue];
            departModel.Sequence = [[index objectForKey:@"sequence"] intValue];
            departModel.DepartName = [index objectForKey:@"name"];
            departModel.DeptFatherID = [index objectForKey:@"pid"];
            departModel.IsDel = [[index objectForKey:@"isDel"] boolValue];
            NSNumber *infoState = [index objectForKey:@"infoState"];
            departModel.InfoState = [NSString stringWithFormat:@"%lld", [infoState longLongValue]];
            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
            [depMgr insertDepartment:departModel];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
            });
        } else if ([type isEqualToString:@"deptUpdate"]) {
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            NSString *depId = [index objectForKey:@"id"];
            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
            CDepartmentModel *departModel = [depMgr loadDepartment:depId];
            departModel.UserNum = [[index objectForKey:@"userNum"] intValue];
            departModel.Sequence = [[index objectForKey:@"sequence"] intValue];
            departModel.DepartName = [index objectForKey:@"name"];
            departModel.DeptFatherID = [index objectForKey:@"pid"];
            departModel.IsDel = [[index objectForKey:@"isDel"] boolValue];
            NSNumber *infoState = [index objectForKey:@"infoState"];
            departModel.InfoState = [NSString stringWithFormat:@"%lld", [infoState longLongValue]];
            [depMgr updateDepartment:departModel];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
            });
        } else if ([type isEqualToString:@"deptDelete"]) {
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSString *depId = [index objectForKey:@"id"];
            CDepartmentMgr *depMgr = [[CDepartmentMgr alloc] init];
            [depMgr updateDepartmentIsdelWithDeptId:depId IsDel:NO];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEORGNAZATION object:nil];
            });
        } else if ([type isEqualToString:@"forceOffline"]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDIDFORCEQUIT object:sudic];
            });
            
        } else if ([type isEqualToString:@"returnGroupUpdate"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(GroupId)) {
                
//                CGroupModel  *groupModel = [[CGroupModel alloc] init];
                CGroupModel *groupModel = [[[CGroupMgr alloc]init] loadGroup:GroupId];
                if (![groupModel.GroupNotice isEqualToString:[index stringForKey:@"notice"]]) {
                    groupModel.yuLiuZiduan3 = @"haveNewNotice";
                }
                groupModel.GroupId = GroupId;
                groupModel.IsDel = NO;
                groupModel.GroupName = [index stringForKey:@"name"];
                groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                groupModel.GroupNotice = [index stringForKey:@"notice"];
                groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"name"]] lowercaseString];
               BOOL ret =  [gropuMgr insertGroup:groupModel];
                if (ret) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEGROUPINFO object:nil];
                    });
                    
                }
            }
            
           
            
            
        }
        else if ([type isEqualToString:@"returnGroupDel"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            [gropuMgr updateGroupIsDelWithGroupId:[NSString stringWithFormat:@"%@",[index objectForKey:@"groupCode"]] IsDel:YES];
            [mesMgr delGroupMessageWithGroupId:[index objectForKey:@"groupCode"]];
            [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:[index objectForKey:@"groupCode"]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPUPDATEGROUPLIST object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
//                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
            });
            
        } else if ([type isEqualToString:@"returnUpdateGroupMember"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSString *groupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(groupId)) {
                
                CGroupModel *groupModel = [[CGroupModel alloc] init];
                groupModel.GroupId = groupId;
                groupModel.GroupName = [index stringForKey:@"groupName"];
                groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                groupModel.OwnerId = [index stringForKey:@"ownerId"];
                groupModel.UserNum = [index integerForKey:@"groupCount"];
                groupModel.OwnerName = [index stringForKey:@"ownerName"];
                groupModel.GroupNotice = [index stringForKey:@"notice"];
                groupModel.IsDel = NO;
                groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"groupName"]] lowercaseString];
                [gropuMgr insertGroup:groupModel];
                
                NSString *addMembers = [index objectForKey:@"addMembers"];
                NSString *delMembers = [index objectForKey:@"delMembers"];
                CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                NSArray *addArray = [addMembers componentsSeparatedByString:@","];
                NSArray *delArray = [delMembers componentsSeparatedByString:@","];
                
                if (addArray.count > 0) {
                    NSMutableArray *addArrayM = [NSMutableArray array];
                    [addArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                        if (obj.length > 3) {
                            CGroupMemberModel *groupmemberModel = [[CGroupMemberModel alloc] init];
                            groupmemberModel.GroupID = groupModel.GroupId;
                            groupmemberModel.UserId = obj;
                            [addArrayM addObject:groupmemberModel];
                            groupmemberModel = nil;
                        }
                    }];
                    [groupMemMgr batchInsertGroupMember:addArrayM];
                }
                if (delArray.count > 0) {
                    [delArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                        if (obj.length > 3) {
                            if ([obj isEqualToString:curModel.UserID]) {
                                [gropuMgr updateGroupIsDelWithGroupId:groupModel.GroupId IsDel:YES];
                                [mesMgr delGroupMessageWithGroupId:groupModel.GroupId];
                            
                                [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:groupModel.GroupId];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                                    //                                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                                });
                            }
                            [groupMemMgr delGroupMemberWithUserId:obj groupId:groupId];
                            
                        }
                        
                    }];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPUPDATEGROUPLIST object:nil];
            });
        } else if ([type isEqualToString:@"returnExitGroup"]) {
        
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            if ([curModel.UserID isEqualToString:[index objectForKey:@"userId"]]) {
                [gropuMgr updateGroupIsDelWithGroupId:[index stringForKey:@"groupId"] IsDel:YES];
                [mesMgr delGroupMessageWithGroupId:[index stringForKey:@"groupId"]];
                 [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:[index objectForKey:@"groupId"]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
//                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                });
                

            } else {
                NSString *groupId = [index objectForKey:@"groupId"];
                if (!M_ISSTRNULL(groupId)) {
                        
                       CGroupModel *groupModel = [[CGroupModel alloc] init];
                        groupModel.GroupId = [index objectForKey:@"id"];
                        groupModel.GroupName = [index stringForKey:@"groupName"];
                    
                        groupModel.UserNum = [index integerForKey:@"groupCount"];
                        groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                        groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"groupName"]] lowercaseString];
                        [gropuMgr insertGroup:groupModel];
                    }
                
                CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                
                [groupMemMgr delGroupMemberWithUserId:[index objectForKey:@"userId"] groupId:groupId];
                
            }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPUPDATEGROUPLIST object:nil];
                });
            } else if ([type isEqualToString:@"returnGroupCreat"]) {
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(GroupId)) {
                CGroupModel  *groupModel = [[CGroupModel alloc] init];
                groupModel.GroupId = GroupId;
                groupModel.GroupName = [index stringForKey:@"name"];
                groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                groupModel.OwnerId = [index stringForKey:@"ownerId"];
                groupModel.UserNum = [index integerForKey:@"userCount"];
                groupModel.OwnerName = [index stringForKey:@"owner"];
                groupModel.GroupNotice = [index stringForKey:@"notice"];
                groupModel.IsDel = NO;
                groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"name"]] lowercaseString];
                [gropuMgr insertGroup:groupModel];
            }
                
            
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPUPDATEGROUPLIST object:nil];
                });

                
            }
            else if ([type isEqualToString:@"returnGroupDeleMember"]) {
                NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                if (index == nil) {
                    return;
                }
                NSString *GroupId = [index objectForKey:@"groupId"];
                if (!M_ISSTRNULL(GroupId)) {
                    NSString *delMembers = [index objectForKey:@"delMembers"];
                    CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                    if (!M_ISSTRNULL(delMembers)) {
                        NSArray *delArray = [delMembers componentsSeparatedByString:@","];
                        
                        if (delArray.count > 0) {
                            [delArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                                if (obj.length > 3) {
                                    if ([obj isEqualToString:curModel.UserID]) {
                                        [gropuMgr updateGroupIsDelWithGroupId:GroupId IsDel:YES];
                                        [mesMgr delGroupMessageWithGroupId:GroupId];
                                        [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:GroupId];
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                                            //                                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                                        });
                                    }
                                    [groupMemMgr delGroupMemberWithUserId:obj groupId:GroupId];
                                    
                                }
                                
                            }];
                        }
                        
                    }

                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPUPDATEGROUPLIST object:nil];
                });
                
                
            } else if ([type isEqualToString:@"returnTalkOverGroupCreat"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(GroupId)) {
                CGroupModel  *groupModel = [[CGroupModel alloc] init];
                groupModel.GroupId = GroupId;
                groupModel.GroupName = [index stringForKey:@"name"];
                groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                groupModel.OwnerId = [index stringForKey:@"ownerId"];
                groupModel.UserNum = [index integerForKey:@"groupCount"];
                groupModel.OwnerName = [index stringForKey:@"ownerName"];
                groupModel.GroupNotice = [index stringForKey:@"notice"];
                groupModel.isShow = [index boolForKey:@"isHidden"];
                groupModel.groupType = 1;
                groupModel.GroupCreateDate = [index stringForKey:@"createDate"];
                groupModel.IsDel = NO;
                groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"name"]] lowercaseString];
                [gropuMgr insertGroup:groupModel];
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });

        } else if ([type isEqualToString:@"returnUpdateTalkOverGroupMember"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(GroupId)) {
                
                CGroupModel  *groupModel = [[CGroupModel alloc] init];
            
                    groupModel.GroupId = GroupId;
                    groupModel.GroupName = [index stringForKey:@"groupName"];
                    groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                    groupModel.OwnerId = [index stringForKey:@"ownerId"];
                    groupModel.UserNum = [index integerForKey:@"groupCount"];
                    groupModel.OwnerName = [index stringForKey:@"ownerName"];
                    groupModel.GroupNotice = [index stringForKey:@"notice"];
                    groupModel.isShow = [index boolForKey:@"isHidden"];
                    groupModel.groupType = 1;
                    groupModel.GroupCreateDate = [index stringForKey:@"createDate"];
                    groupModel.IsDel = NO;
                    groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                    groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"groupName"]] lowercaseString];
                    [gropuMgr insertGroup:groupModel];
                    
                    
                    NSString *addMembers = [index objectForKey:@"addMembers"];
                    NSString *delMembers = [index objectForKey:@"delMembers"];
                    CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                    if (!M_ISSTRNULL(addMembers)) {
                        NSArray *addArray = [addMembers componentsSeparatedByString:@","];
                        
                        if (addArray.count > 0) {
                            NSMutableArray *addArrayM = [NSMutableArray array];
                            [addArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                                if (obj.length > 3) {
                                    CGroupMemberModel *groupmemberModel = [[CGroupMemberModel alloc] init];
                                    groupmemberModel.GroupID = groupModel.GroupId;
                                    groupmemberModel.UserId = obj;
                                    [addArrayM addObject:groupmemberModel];
                                    groupmemberModel = nil;
                                }
                            }];
                            [groupMemMgr batchInsertGroupMember:addArrayM];
                        }
                        
                    }
                    if (!M_ISSTRNULL(delMembers)) {
                        NSArray *delArray = [delMembers componentsSeparatedByString:@","];
                        
                        if (delArray.count > 0) {
                            [delArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                                if (obj.length > 3) {
                                    if ([obj isEqualToString:curModel.UserID]) {
                                        [gropuMgr updateGroupIsDelWithGroupId:groupModel.GroupId IsDel:YES];
                                        [mesMgr delGroupMessageWithGroupId:groupModel.GroupId];
                                        [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:groupModel.GroupId];
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                                            //                                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                                        });
                                    }
                                    [groupMemMgr delGroupMemberWithUserId:obj groupId:GroupId];
                                    
                                }
                                
                            }];
                        }
                        
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
                    });

                
            }
            
           
            
        } else if ([type isEqualToString:@"returnTalkOverGroupUpdate"]) {
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"id"];
            if (!M_ISSTRNULL(GroupId)) {
                CGroupModel  *groupModel = [gropuMgr loadGroup:GroupId];
                if (groupModel) {
                    
                    groupModel.GroupId = GroupId;
                    groupModel.GroupName = [index stringForKey:@"name"];
                    groupModel.GroupIntroduction = [index stringForKey:@"introduction"];
                    groupModel.GroupNotice = [index stringForKey:@"notice"];
                    groupModel.isShow = [index boolForKey:@"isHidden"];
                    groupModel.groupType = 1;
                    groupModel.IsDel = NO;
                    groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                    groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"name"]] lowercaseString];
                    [gropuMgr updateGroup:groupModel];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
                    });
                }

            }

            
        } else if ([type isEqualToString:@"returnTalkOverGroupDeleMember"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            if (index == nil) {
                return;
            }
            NSString *GroupId = [index objectForKey:@"groupId"];
            if (!M_ISSTRNULL(GroupId)) {
                CGroupModel  *groupModel = [gropuMgr loadGroup:GroupId];
                if (groupModel) {
                    groupModel.GroupId = GroupId;
                    groupModel.UserNum = [index integerForKey:@"groupCount"];
                    [gropuMgr updateGroup:groupModel];
                    
                    
                    NSString *delMembers = [index objectForKey:@"delMembers"];
                    CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                    if (!M_ISSTRNULL(delMembers)) {
                        NSArray *delArray = [delMembers componentsSeparatedByString:@","];
                        
                        if (delArray.count > 0) {
                            [delArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                                if (obj.length > 3) {
                                    if ([obj isEqualToString:curModel.UserID]) {
                                        [gropuMgr updateGroupIsDelWithGroupId:groupModel.GroupId IsDel:YES];
                                        [mesMgr delGroupMessageWithGroupId:groupModel.GroupId];
                                        [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:groupModel.GroupId];
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                                            //                                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                                        });
                                    }
                                    [groupMemMgr delGroupMemberWithUserId:obj groupId:GroupId];
                                    
                                }
                                
                            }];
                        }
                        
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
                    });

                }
                
            }
            
           
            
        } else if ([type isEqualToString:@"returnExitTalkOverGroup"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            if ([curModel.UserID isEqualToString:[index objectForKey:@"userId"]]) {
                [gropuMgr delGroupWithGroupId:[index stringForKey:@"groupId"]];
                [mesMgr delGroupMessageWithGroupId:[index stringForKey:@"groupId"]];
                [[[CMessageDraftMgr alloc] init] delMessageDraftWithGroupId:[index objectForKey:@"groupId"]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPUPDATEMESSAGERECORD object:nil];
                    //                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDeleteGroup object:nil];
                });
                
                
            } else {
                NSString *groupId = [index objectForKey:@"groupId"];
                if (!M_ISSTRNULL(groupId)) {
                    
                    CGroupModel *groupModel = [[CGroupModel alloc] init];
                    groupModel.GroupId = [index objectForKey:@"id"];
                    groupModel.GroupName = [index stringForKey:@"groupName"];
                    
                    groupModel.UserNum = [index integerForKey:@"groupCount"];
                    groupModel.PinYin = [[[NSString pinyinWithHanzi:groupModel.GroupName] lowercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
                    groupModel.firstLetter = [[NSString namToPinYinFisrtNameWith:[index objectForKey:@"groupName"]] lowercaseString];
                    [gropuMgr insertGroup:groupModel];
                }
                
                CGroupMemberMgr *groupMemMgr = [[CGroupMemberMgr alloc] init];
                
                [groupMemMgr delGroupMemberWithUserId:[index objectForKey:@"userId"] groupId:groupId];
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:k_XMPPGETDISCUSSIONLIST object:nil];
            });

            
        } else if ([type isEqualToString:@"returnAddReleaseContent"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            EFengShare *share = [EFengShare objectWithKeyValues:index];
            
            
            [[[CShareMgr alloc] init] insertWithShare:share];
            [[[CSharePersonMgr alloc] init] insertWithShare:share];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPReceiveShare object:nil];
            });
            
            
        } else if ([type isEqualToString:@"returnDelReleaseContent"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            EFengShareDel *share = [EFengShareDel objectWithKeyValues:index];
            [[[CShareDelMgr alloc] init] insertWithShareDel:share];
            [[[CShareMgr alloc] init] delShareWithShareId:share.shareId];
            [[[CSharePersonMgr alloc] init] delShareWithShareId:share.shareId];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDelShare object:@[share.shareId]];
            });
            
            
        } else if ([type isEqualToString:@"returnAddContentReply"]) {
            
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            
            CShareCommentMgr *comMgr = [[CShareCommentMgr alloc] init];
            EFengContent *comment = [EFengContent objectWithKeyValues:index];
            if ([comment.sendUserId isEqualToString:curModel.UserID]) {
                comment.isRead = YES;
            }
            [comMgr insertWithShareComment:comment];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPReceiveComment object:nil];
            });
            
            
        } else if ([type isEqualToString:@"returnDelContentReply"]) {
            
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            EFengShareCommentDel *share = [EFengShareCommentDel objectWithKeyValues:index];
            
            [[[CShareCommentMgr alloc] init] delShareCommentWithCommentId:share.commentId];
            [[[CShareCommentDelMgr alloc] init] insertCommentDelWithCommentDel:share];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPDelComment object:nil];
            });
            
            
        }else if ([type isEqualToString:@"returnUploadFileSizeLimit"]){
            NSDictionary *index = [NSJSONSerialization JSONObjectWithData:[[NSString stringWithFormat:@"%@",[sudic objectForKey:@"body"]] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            [USER_DEFAULT setObject:[NSString stringWithFormat:@"%@",[index objectForKey:@"uploadFileSizeLimit"]] forKey:FILEMAXSIZE];
            [USER_DEFAULT synchronize];
        }
        else if ([type isEqualToString:@"shke"])
        {
            CMessageModel *model = [[CMessageModel alloc] init];
            model.MessageContent = @"向您发送了一个窗口抖动";
            model.Stream = [sudic stringForKey:@"stream"];
            model.FileSize = [NSString stringWithFormat:@"%@",[sudic objectForKey:@"length"]];
            model.yuLiuZiduan1 = [sudic stringForKey:@"companyId"];
            NSString *nodeId =[[sudic stringForKey:@"nodeId"] stringByReplacingOccurrencesOfString:@"-" withString:@""];
            model.MessageId = [NSString stringWithFormat:@"%@-%@",[sudic objectForKey:@"messageId"],nodeId];
            model.TimeStamp = [NSString stringWithFormat:@"%@",[sudic objectForKey:@"sendTime"]];
            model.FriendUserId = [sudic stringForKey:@"fromId"];
            model.MineUserId = [sudic stringForKey:@"toId"];
            model.SoundPlayStatus = MessageSoundNotPlay;
            model.MessageSendedStatus = kMessageOK;
            model.FriendUserName = [sudic stringForKey:@"fromName"];
            model.MineUserName = [sudic stringForKey:@"toName"];
            model.MessageType = [sudic stringForKey:@"type"];
            //model.MessageType = @"text";
            model.IsShowInmessageList = YES;
            CContactModel *contact = [conMgr loadNotDelContactWithUserId:model.FriendUserId];
            if (contact) {
                //bug 9337 fixed by lixu
                contact.compCode = [sudic stringForKey:@"companyId"];
                [conMgr insetContact:contact];
                if (contact.messageSettingType == MESSAGESETTING_RECEVIEDNOTREMIND) {
                    model.ReadStatus = YES;
                    
                }
            } else {
                if (![[message.from.user componentsSeparatedByString:@"_"].lastObject isEqualToString:[message.to.user componentsSeparatedByString:@"_"].lastObject]) {
                    contact = [[CContactModel alloc] init];
                    contact.PinYin = [[[NSString pinyinWithHanzi:model.FriendUserName] lowercaseString]  stringByReplacingOccurrencesOfString:@" " withString:@""];
                    contact.UserCode = message.from.user;
                    contact.UserID = model.FriendUserId;
                    contact.UserName = model.FriendUserName;
                    contact.compCode = [sudic stringForKey:@"companyId"];
                    contact.yuLiuZiduan3 = @"isWaibu";
                    [conMgr insetContact:contact];
                }
            }
            if (contact) {
                
                
              [mesMgr insertMessage:model];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    BOOL ishasVoice = NO;
                    if (model.ReadStatus == NO) {
                        if (!isDisturb) {
                            if (contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND && userSetting.Shake) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemAlert];
                                }
                                
                                
                            }
                            if (contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND && userSetting.Voice) {
                                if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
                                    [UIUtil playSystemSoundForMessage];
                                    
                                }
                                ishasVoice = YES;
                            }
                            
                        }
                        
                    }
                    if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && ![[sudic stringForKey:@"fromId"] isEqualToString:curModel.UserID] && contact.messageSettingType == MESSAGESETTING_RECEVIEDANDREMIND)
                    {
                        self.noticeNum ++;
                        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                        localNotification.alertAction = @"查看";
                        if (ishasVoice) {
                            localNotification.soundName = UILocalNotificationDefaultSoundName;
                        }
                        if ([model.MessageType isEqualToString:@"file"]) {
                            localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一个文件"];
                        } else if ([model.MessageType isEqualToString:@"image"]){
                            localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一张图片"];
                        } else if ([model.MessageType isEqualToString:@"voice"]){
                            localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,@"发来一段语音"];
                        } else if ([model.MessageType isEqualToString:@"text"]) {
                            localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,model.MessageContent];
                        }else if ([model.MessageType isEqualToString:@"shke"]) {
                            localNotification.alertBody = [NSString stringWithFormat:@"%@:%@",model.FriendUserName,model.MessageContent];
                        }
                        localNotification.applicationIconBadgeNumber = self.noticeNum;//标记数
                        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];//发送通知
                    }
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPRECEIVEMESSAGE object:nil];
                    
                    
                });
                
            }
        }
       else if ([type isEqualToString:@"UserHostHandupTelCall"]||[type isEqualToString:@"UserHandupTelCall"]||[type isEqualToString:@"UserTelCall"])
       {
           NSLog(@"body体%@",body);
           NSLog(@"子字典%@",sudic);
       }


    }

    }
    });
}

- (void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error
{
    CMessageMgr *messageMgr = [[CMessageMgr alloc] init];
    NSString *body = [[message elementForName:@"body"] stringValue];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    NSDictionary *subDic = dict[@"messageCommon"];
    NSString *MessageId = [NSString stringWithFormat:@"%@",[subDic objectForKey:@"messageId"]];
    if (MessageId) {
        CMessageModel *model = [messageMgr loadMessageWithMessageId:MessageId];
        model.MessageSendedStatus = kMessageSendFailed;
        if([messageMgr updateMessage:model])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:K_XMPPFAILEDRECEIVEMESSAGE object:model.MessageId];
                
            });
        }

    }
   
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
//    DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [presence fromStr]);
//    NSLog(@"presence from:%@, status:%@ show:%@", [presence from], [presence status],[presence show]);
    
//    dispatch_async(self.xmppMgrQueen, ^{
    
        [self handlePresence:presence sender:sender];
//    });
    
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPRosterDelegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


- (void)delDepNumberWithDepId:(NSString *)depId depMgr:(CDepartmentMgr *)depMgr
{
    CDepartmentModel *dep = [depMgr loadDepartment:depId];
    if (dep) {
        dep.UserNum = dep.UserNum - 1;
        [depMgr updateDepartment:dep];
        if (dep.DeptFatherID.length > 0 && dep.DeptFatherID.integerValue != 0) {
            [self delDepNumberWithDepId:dep.DeptFatherID depMgr:depMgr];
        }
    }
}


- (void)addDepNumberWithDepId:(NSString *)depId depMgr:(CDepartmentMgr *)depMgr
{
    CDepartmentModel *dep = [depMgr loadDepartment:depId];
    if (dep) {
        dep.UserNum = dep.UserNum + 1;
        [depMgr updateDepartment:dep];
        if (dep.DeptFatherID.length > 0 && dep.DeptFatherID != 0) {
            [self addDepNumberWithDepId:dep.DeptFatherID depMgr:depMgr];
        }

    }
}
@end
